Im trying to write a generic function that receives an instance of a type "Location" and a list of objects - where each one of the objects has a field of this "location" type how do I get the value of each one of the "locations" in the list? theres more to thecode but this is the only relevant part
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);
}
}
CodePudding user response:
To get a Location
, first, you need to ensure that all items in toFindIn
list have the property. You could add an interface to ensure that, then you could use a generic type constraint.
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;
}
//...
}
}
CodePudding user response:
One way is to use an interface:
interface IHasLocation
{
Location Location { get; }
}
Then constrain 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;
//...
}
Or if you can't do that, you can pass a function:
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);
//...
}
Which can be called like this:
class SomethingWithALocation
{
public Location Location { get; }
}
var list = new List<SomethingWithALocation>();
var something = someLocation.SmallestDistance(list, item => item.Location);