如何声明并初始化继承自泛型抽象类MyData<T>的类成员?
解决方案
1. 成员X的正确声明
你之前的误解是关键:抽象类完全可以作为变量类型,变量存储的是它的子类实例即可。所以private MyData<PrimType> X这个声明是合法的,语法上没有问题,只要后续给它赋值对应的子类实例就行。
2. 实现类型匹配的工厂逻辑
要根据泛型参数返回对应MyData<T>子类实例,需要注意几个细节:
- 类型判断要用
typeof(PrimType) == typeof(int)这类正确语法 - 每个子类必须正确继承
MyData<T>(比如IntConcreteDataType : MyData<int>) - 因为C#泛型类不支持协变,需要通过
object中转做类型转换
完整代码示例
第一步:定义抽象类与子类
public abstract class MyData<T> { // 示例抽象方法,根据你的需求修改 public abstract void ProcessValue(T value); } // int类型的具体实现 public class IntConcreteData : MyData<int> { public override void ProcessValue(int value) { Console.WriteLine($"处理整数:{value}"); } } // double类型的具体实现 public class DoubleConcreteData : MyData<double> { public override void ProcessValue(double value) { Console.WriteLine($"处理浮点数:{value}"); } } // string类型的具体实现 public class StringConcreteData : MyData<string> { public override void ProcessValue(string value) { Console.WriteLine($"处理字符串:{value}"); } }
第二步:实现MyClass(原TestingClass)
class MyClass<PrimType> { // 合法声明:用抽象类作为变量类型,存储子类实例 private MyData<PrimType> X; public MyClass() { X = CreateMyDataInstance(); } // 工厂方法:根据泛型参数返回对应子类实例 private MyData<PrimType> CreateMyDataInstance() { var targetType = typeof(PrimType); if (targetType == typeof(int)) { // 通过object中转实现类型转换 return (MyData<PrimType>)(object)new IntConcreteData(); } else if (targetType == typeof(double)) { return (MyData<PrimType>)(object)new DoubleConcreteData(); } else if (targetType == typeof(string)) { return (MyData<PrimType>)(object)new StringConcreteData(); } else { throw new NotSupportedException($"不支持类型:{targetType.Name}"); } } // 对外暴露功能的示例方法 public void RunProcess(PrimType value) { X.ProcessValue(value); } }
第三步:实例化MyClass
直接指定泛型参数,编译器会自动匹配对应的工厂分支:
// 实例化int版本 var intClass = new MyClass<int>(); intClass.RunProcess(123); // 输出:处理整数:123 // 实例化double版本 var doubleClass = new MyClass<double>(); doubleClass.RunProcess(45.67); // 输出:处理浮点数:45.67 // 实例化string版本 var stringClass = new MyClass<string>(); stringClass.RunProcess("测试文本"); // 输出:处理字符串:测试文本
可选优化:抽离独立工厂类
如果多个类需要复用这个实例创建逻辑,可以把工厂抽成静态类:
public static class MyDataFactory { public static MyData<T> Create<T>() { var targetType = typeof(T); if (targetType == typeof(int)) return (MyData<T>)(object)new IntConcreteData(); else if (targetType == typeof(double)) return (MyData<T>)(object)new DoubleConcreteData(); else if (targetType == typeof(string)) return (MyData<T>)(object)new StringConcreteData(); else throw new NotSupportedException($"不支持类型:{targetType.Name}"); } }
然后在MyClass里直接调用:
X = MyDataFactory.Create<PrimType>();
内容的提问来源于stack exchange,提问作者icaro amorim
相关产品推荐
相关产品推荐

