繁体   English   中英

实例化继承自 Abstract MyType 的 object<t></t>

[英]Instantiate object that inherits from Abstract MyType<T>

我想要一个 class (MyClass),它有一个名为 X 的成员。X 是从抽象 class MyData 继承的变量。 MyData 有多个继承者。 T 可以是任何原始数据类型(int、double、strings...)。 如何在 class 中声明此数据成员 X,以及如何在实例化 MyClass 时正确初始化它?

我曾尝试使用 generics 但仍然没有找到正确的方法。 由于 MyData 是抽象的并且具有通用类型,所以我真的不能拥有一个给定类型的工厂,让我们假设 Int 返回从 MyData 继承的具体类型,或者我可以吗?

    class TestingClass<PrimType> {
    private MyData<PrimType> X //This is not allowed (X inherits from MyData<T> which is abstract) how do I achieve this?;
 
    public TestingClass() {
        X = InnstantiateMyData();

      }
     //What the signature of this should be?
     public MyData<PrimType> InstantiateMyData(){
           var type = typeof(PrimType)
           if(PrimType == int)
             return IntConcreteDataType;//IntConcreteDataType would be a concrete inheritor from MyData<T>
             ...
      }
    }
    

 public abstract class MyData<T>
    {
       //only methods...
     }

您的工厂方法的签名很好,您需要对主体进行两项更改才能使其编译:

 public MyData<PrimType> InstantiateMyData(){
       var type = typeof(PrimType)
       if(type == typeof(int)) //<— comparing Type
         return (MyData<PrimType>)(object) new IntConcreteDataType();//constructing a concrete instance, casting to abstract generic via System.Object
         ...
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM