0

我有一个 linq 查询,它当前正在基于泛型类型参数进行对象实例化。我实际上需要实例化泛型参数的更具体的子类。有没有办法用派生类型进行实例化?如有必要,我愿意使用反射甚至直接 IL 发射,但如果可能的话,我想尝试对基类的属性进行类型检查。

所以我的代码是这样的:

IQueryable<TType> myObjects = from blah in blahblah
                              select new TType
                              {
                                   PropertyA = someValue;
                                   PropertyB = someOtherValue;
                              }

但我需要 IQueryable 中的对象实际上是 TType 的派生类。我事先不知道它们将是哪个派生类,只是它们都是基于其他逻辑的相同派生类型。

4

1 回答 1

1

听起来你需要一个工厂模式:

from blah in blahblah
select BaseTypeFactory.Create(/* parameters/objects necessary to create the BaseType*/)

然后BaseTypeFactory它会做它需要做的任何事情来吐出正确的派生BaseType实例。

如果(如您的评论所说)TType被限制为特定的基本类型,则工厂可能看起来像:

(假设TType受 约束where TType : BaseType

public void BaseType TTypeFactory.Create(/* parameters/objects needed to create Base Types*/)
{
    // full of assumptions, modify to fit your needs:
    switch( typeID /*or some othervariable designating type to create*/)
    case 1: // DerivedType 1
        return new DerivedType1 { /* initialization parameters */ };
        break;
    case 2:
        return new DerivedType2 { /* initialization parameters */ };
        break;
    // etc.

}
于 2012-12-06T15:41:56.743 回答