小编Mal*_*a99的帖子

如何向下转换静态方法生成的实例?

我有一个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");

因为我想分析某些类型的文件进入ParentChild实例,我想保留通过静态方法生成实例设计.

我该childInstance怎么办?

c#

12
推荐指数
1
解决办法
871
查看次数

标签 统计

c# ×1