据我所知,在C#2.0中无法执行以下操作
public class Father
{
public virtual Father SomePropertyName
{
get
{
return this;
}
}
}
public class Child : Father
{
public override Child SomePropertyName
{
get
{
return this;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我通过在派生类中将属性创建为"new"来解决问题,但当然这不是多态的.
public new Child SomePropertyName
Run Code Online (Sandbox Code Playgroud)
2.0中有什么解决方案吗?3.5中解决此问题的任何功能如何?
好的,所以我承认这是有点棘手......但它确实有逻辑作用.我正在使用C#作为当前项目,我正试图找到一种方法来覆盖派生类中的成员变量,但是在基类方法中访问重写的变量.为了使事情更"有趣",如果被覆盖的成员变量是静态的(这在下面的示例代码中没有显示)将是更好的选择.
这是我的示例代码:
class baseclass
{
protected string[] array = null;
public string method()
{
string str = "";
foreach (string x in this.array)
{
str += x + " ";
}
return str;
}
}
class subclass1 : baseclass
{
new string[] array = new string[]
{
"class1value1",
"class1value2",
"class1value3",
"class1value4"
};
}
class subclass2 : baseclass
{
new string[] array = new string[]
{
"class2value1",
"class2value2",
"class2value3",
"class2value4"
};
}
Run Code Online (Sandbox Code Playgroud)
有什么想法,为什么这不起作用,以及解决它的方法?