我有一个C#程序的问题,包括以下内容:
class Program
{
static void Main(string[] args)
{
Child childInstance = Child.ParseFromA(@"path/to/Afile") as Child;
}
}
class Parent{
int property;
public static Parent ParseFromA(string filename)
{
Parent parent = new Parent();
// parse file and set property here...
return parent;
}
}
class Child : Parent
{
public void SomeAdditionalFunction() { }
}
Run Code Online (Sandbox Code Playgroud)
运行此代码时,childInstance变为null.
我尝试使用显式转换进行以下赋值,但以异常结束:
Child childInstance = (Child)Child.ParseFromA(@"path/to/Afile");
因为我想分析某些类型的文件进入Parent和Child实例,我想保留通过静态方法生成实例设计.
我该childInstance怎么办?
Hei*_*nzi 23
你不能低估它.一旦将对象创建为a Parent,它将始终是a Parent.这就像试图将a向下转换new object()为a string:那是行不通的 - 这个字符串应该代表哪个字符序列?
因此,您唯一的解决方案是创建正确的对象.我在你的案例中看到的唯一选择是使你的静态方法通用:
public static T ParseFromA<T>(string filename) where T : Parent, new()
{
T t = new T();
// parse file and set property here...
return t;
}
Run Code Online (Sandbox Code Playgroud)
用法:
Child childInstance = Parent.ParseFromA<Child>(@"path/to/Afile");
Run Code Online (Sandbox Code Playgroud)
泛型约束T : Parent确保它T是子类型Parent,并new()确保T具有无参数构造函数.
| 归档时间: |
|
| 查看次数: |
871 次 |
| 最近记录: |