我想从基构造函数调用子类构造函数,并将创建的子类对象作为基类对象。 代码如下所示。
class Text
{
public string OriginalText;
public Text() { }
public Text(string text)
{
OriginalText = text;
text = FormatText(text); // like text.ToUpper().Trim()
if (Category1.Check(text))
new Category1(text);
else if (Category2.Check(text))
new Category2(text);
else if (Category3.Check(text))
new Category3(text);
}
}
class Category1 : Text
{
public string Property1;
public Category1(string text)
{
Property1 = text + "#1";
}
static public bool Check(string text)
{
return text == "category1";
}
}
class Category2 : Text
{
public string Property2;
public Category2(string text)
{
Property2 = text + "(2)";
}
static public bool Check(string text)
{
return text == "category2";
}
}
class Category3 : Text
{
public string Property3;
public Category3(string text)
{
Property3 = text + "%3";
}
static public bool Check(string text)
{
return text == "category3";
}
}
但是,var t = new Text("category1")
不是子类的对象。我通过评估 t is Category1
来检查,结果是 false
。我尝试添加
return
位于 new Category1(text)
前面,但由于构造函数返回 void 类型,因此此方法失败。以下是从日语翻译的错误消息。
An object statement can't be used after the keyword return since MainWindow.Text.Text(string)' returns void type
解决这个问题的一种方法是定义一个返回子类对象的静态方法。
static public Text GetCategory(string text)
{
text = FormatText(text);
if (Category1.Check(text))
return new Category1(text);
else if (Category2.Check(text))
return new Category2(text);
else if (Category3.Check(text))
return new Category3(text);
return null;
}
但是,这次无法使用 OriginalText = text;
,因为这是静态方法。我承认可以通过将以下代码添加到每个
if
语句的单个内容
string tmp1 = text;
text = FormatText(text);
var c1 = new Category1(text);
c1.OriginalText = tmp1;
return c1;
或在每个子类构造函数中设置OriginalText
。
但这会使代码冗长、冗余并且难以阅读和维护。我想将公共(public)进程聚合在同一个地方,我的意思是,基本构造函数。
谷歌搜索“call subclass constructor c#”给了我两篇文章,但这些文章对我来说并不是答案。
Calling subclass constructor from static base class method
这是无关紧要的。它是关于调用从基类继承的静态子类方法。How to call subclass constructor only in inheritence
这是不同的。这是关于调用子类构造函数而不调用基类构造函数。
我该如何处理这个问题?
最佳答案
在您正在讨论的代码块中,您正在创建一个新实例,但它从未分配给变量,也不能从构造函数返回:
if (Category1.Check(text))
new Category1(text); // <-- wrong!
构造函数是一种初始化给定类型在内存中新创建的空间的方法。您无法从构造函数更改类型!
您想要一个工厂模式,就像您在第二个示例中给出的那样。这是你最好也是唯一的选择:
static public Text GetCategory(string text)
{
text = FormatText(text);
if (Category1.Check(text))
return new Category1(text);
关于c# - 在 C# 中从基构造函数调用子类构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47756528/