我試圖撰寫一個通用函式,它接收一個“位置”型別的實體和一個物件串列——其中每個物件都有一個這個“位置”型別的欄位,我如何獲得每個“位置”型別的值位置”在串列中?代碼還有更多,但這是唯一相關的部分
public static T SmallestDistance<T>(this Location current, List<T> toFindIn)
{
double minDis = double.MaxValue;
foreach(T cur in toFindIn )
{
Location temp = typeof(T).GetProperty(typeof(Location).Name).GetValue(cur);
}
}
uj5u.com熱心網友回復:
要獲得Location,首先,您需要確保toFindIn串列中的所有專案都具有該屬性。您可以添加一個介面來確保這一點,然后您可以使用泛型型別約束。
public class Location
{
/// ...
}
public interface ILocationHolder
{
Location Location { get; }
}
public static class ExtensionsClass
{
public static T SmallestDistance<T>(this Location current, List<T> toFindIn) where T : ILocationHolder
{
var minDis = double.MaxValue;
foreach (var cur in toFindIn)
{
var temp = cur.Location;
}
//...
}
}
uj5u.com熱心網友回復:
一種方法是使用介面:
interface IHasLocation
{
Location Location { get; }
}
然后約束T:
public static T SmallestDistance<T>(this Location current, List<T> toFindIn)
where T : IHasLocation
{
double minDis = double.MaxValue;
foreach (T cur in toFindIn)
{
Location temp = cur.Location;
//...
}
或者如果你不能這樣做,你可以傳遞一個函式:
public static T SmallestDistance<T>(
this Location current,
List<T> toFindIn,
Func<T, Location> getLocation)
{
double minDis = double.MaxValue;
foreach (T cur in toFindIn)
{
Location temp = getLocation(cur);
//...
}
可以這樣呼叫:
class SomethingWithALocation
{
public Location Location { get; }
}
var list = new List<SomethingWithALocation>();
var something = someLocation.SmallestDistance(list, item => item.Location);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/363827.html
上一篇:在泛型類中實作泛型介面方法
