[英]Property overriding with accessor
I am trying to add a private set
accessor to an overridden property, but am getting a compile time error: 我正在尝试将
private set
访问器添加到重写的属性,但是遇到编译时错误:
does not have an overridable set accessor
I would add a set
accessor to the interface and abstract base class, but I want the accessor to be private, which you cannot add to an interface or abstract property as it sets its access level. 我会向接口和抽象基类添加一个
set
访问器,但是我希望访问器是私有的,您不能将其添加到接口或抽象属性中,因为它会设置访问级别。
An example of what I mean is below: 我的意思的例子如下:
public interface IMyInterface
{
int MyProperty
{
get;
}
}
public abstract class MyBaseClass : IMyInterface
{
public abstract int MyProperty
{
get;
}
}
public class MyClass : MyBaseClass
{
public override int MyProperty
{
get
{
return 0;
}
private set // does not have an overridable set accessor
{
}
}
}
Is there a way around this? 有没有解决的办法? I'm sure I'm missing something simple here.
我确定我在这里缺少一些简单的东西。
There is no way to change the access level of a method or property in an inherited class, or to add an accessor. 无法更改继承的类中方法或属性的访问级别,也不能添加访问器。
This is the only workaround I can imagine. 这是我能想到的唯一解决方法。
public class MyClass : MyBaseClass
{
private int myField;
public override int MyProperty
{
get { return myField; }
}
private int MyPropertySetter
{
set { myField = value; }
}
}
Well, You can't modify the accessor in the inheritance chain. 好吧,您不能在继承链中修改访问器。 So better option would be just add a
protected set accessor
in your base class. 因此,更好的选择是在基类中添加一个
protected set accessor
。 that will allow you to override the implementation in derived classes. 这样您就可以覆盖派生类中的实现。
What I mean is something like this 我的意思是这样的
public interface IMyInterface
{
int MyProperty
{
get;
}
}
public abstract class MyBaseClass : IMyInterface
{
public abstract int MyProperty
{
get;
protected set;<--add set accessor here
}
}
public class MyClass : MyBaseClass
{
public override int MyProperty
{
get
{
return 0;
}
protected set //this works
{
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.