[英]How to check a list for a different instance of a class inheriting generic interface
我有一个List<ICar<T>>
汽车。 我只想将新的ICar<T>
Honda添加到列表中(如果该列表中尚不存在)。 结构如下:
class Honda : IHonda{}
interface IHonda : ICar<T>
class Ford : IFord{}
interface IFord : ICar<T>
我只想将每种汽车中的一种放入列表中,但只知道它们是ICar<T>
。 我不提前知道可能的汽车清单。 如何才能做到这一点?
我在想类似
cars.Any(i => i.GetType().GetInterfaces().Contains(
car
.GetType()
.GetInterfaces()
.Where(s =>!cars.GetType().GenericTypeArguments != s.GenericTypeArguments
))))
但是,这有点问题,我看不到通过这条道路的道路。
如果您具有与T
对应的Type
实例,则可以使用:
Type t = //
Type carType = typeof(ICar<>).MakeGenericType(t);
bool exists = cars.Any(c => carType.IsAssignableFrom(c.GetType()));
我认为你可以使用
//get list of all interfaces in the currrent car list
//you will have to check the contents of yourList as it may contain some types
//such as IList / IEnumerable that you will want to filter out.
var yourList = list.SelectMany(car => car.GetType().GetInterfaces());
//check get all interfaces on your car and check if the list contains it
bool exists = yourCar.GetType().GetInterfaces().Any(c => yourList.Contains(c));
您也许可以使用类型的完全限定名称来比较元素。
CarTypeComparer compareCarTypes = new CarTypeComparer();
if (!List.contains(car, compareCarTypes))
{
// insert car into list
}
class CarTypeComparer : IEqualityComparer<ICar<T>>
{
public bool Equals(ICar<T> car1, ICar<T> car2)
{
if (car1.GetType().FullName == car2.GetType().Fullname)
{
return true;
}
else
{
return false;
}
}
// implement GetHashCode() ....
}
在ICar接口内添加CarModel属性,然后在您的类中实现它。例如,在Honda类中:
public string CarModel { get { return "Honda"; } }
您可以在查询中检查CarModel属性,当然也可以按CarModel对汽车进行分组,希望对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.