我有包含以下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() { }
}
當運行該代碼,childInstance
變得null
。
我試過下面明確的轉換任務,但有一個例外結束:
Child childInstance = (Child)Child.ParseFromA(@"path/to/Afile");
因爲我想分析某些類型的文件到Parent
和Child
情況下,我想保留通過生成實例設計靜態方法。
我該如何得到一個合適的childInstance
?
謝謝!你的解決方案正是我想要做的! 我應用了它,並完美的工作。 – Malboma99
關於你的例子只是一個小問題:將一個'Animal'轉換成'Cat'是完全理智的:如果它是一個'Cat',你會收到一個'Cat',如果它不是(null)什麼作者)。這裏的問題是,如果你創建一個「動物」,你創建一個抽象的動物,不能成爲一隻貓。這是一個沒有一種類型的模型。如果你談論一個男人,你不是指「約翰」, - 你是指一個抽象的男人。我很確定那是有意的,但我認爲從你的例子來看有點不清楚。 – Archeg
@Archeg:你當然是完全正確的。我修改了我的示例,並決定使用一些框架類。 – Heinzi