3

是否可以检查列表是否包含来自相同基本抽象类的给定(但动态)类型的对象?

主要问题不在于列表,而在于比较类型本身。在单变量和静态变量中,很简单:

if(someVariable is int)

使用静态类型检查列表也很容易,例如:

SomeList.OfType<int>().Any()

或者

(from _Object in SomeList.OfType<int> where _Object is int select _Object).Count() == 0

但如果我要检查的类型是动态的,我无法处理它,fe 作为方法参数传递:

abstract class BasicClass;
class DerivativeOne : BasicClass { }
class DerivativeTwo : BasicClass { }

// in main:

List<BasicClass> _List = new List<BasicClass>();
DerivativeOne a = new DerivativeOne();
DerivativeTwo b = new DerivativeTwo();
DerivativeOne c = new DerivativeOne();

if(!CheckIfTypeExistsInList(a, _List)
{
    _List.Add(a);
}
if(!CheckIfTypeExistsInList(b, _List)
{
    _List.Add(b);
}
if(!CheckIfTypeExistsInList(c, _List)
{
    _List.Add(c);  // this is what I don't want to happen,
           // because I already have one object of type DerivativeOne in my list.
}


// the function:
bool CheckIfTypeExistsInList(BasicClass pObject, List<BasicClass> pList)
{
    /// few attempts:
    pList.OfType<(pObject.GetType()>().Any();  // attempt one, error
    return  (from _Object in SomeList.OfType<(pObject.GetType())> where _Object is int select _Object).Count() == 0;    // attempt two, error
}

PS。我知道代码看起来不整洁,但我试图只展示问题本身,跳过额外的逻辑和东西。

PS2。我知道该问题的解决方案只是将一些属性添加到 BasicClass 并使每个导数都具有该属性的唯一值,但是仍然-我不是在寻找解决问题的另一种途径,我只是如果有可能以“这种”方式做到这一点,则感兴趣。

4

1 回答 1

2

当类型仅在运行时已知时,您不能在不使用反射的情况下在泛型中使用它。但是,您的任务比这更简单 - 您可以使用类型相等来实现您想要的结果:

Type targetType = pObject.GetType();
if (SomeList.Any(o => targetType.Equals(o.GetType()))) {
    ...
}
于 2013-05-25T12:44:48.030 回答