[英]C# How to add a property setter in derived class?
我有一个要求,我有许多类都派生自一个基类。 基类包含也从同一基类派生的子类列表。
所有类都需要能够获取特定值,这些值可以从类本身获取 - 或者 - 它是父类,具体取决于派生类是什么。
我查看了使用方法而不是属性,但是我还想让 .NET 报告组件可以使用这些值,该组件直接访问报告引擎中公开的公共属性,因此排除了方法的使用。
我的问题是在 DerivedClass 中实现 setter 而在 BaseClass 中没有公开可用的 setter 的“最佳实践”方法是什么
public class BaseClass
{
private BaseClass _Parent;
public virtual decimal Result
{
get { return ((_Parent != null) ? _Parent.Result : -1); }
}
}
public class DerivedClass : BaseClass
{
private decimal _Result;
public override decimal Result
{
get { return _Result; }
// I can't use a setter here because there is no set method in the base class so this throws a build error
//set { _Result = value; }
}
}
我无法在 BaseClass 中添加受保护的 setter(如下所示),因为我无法更改 DerivedClass 中的访问修饰符。
public class BaseClass
{
private BaseClass _Parent;
public virtual decimal Result {
get { return ((_Parent != null) ? _Parent.Result : -1); }
protected set { }
}
}
public class DerivedClass : BaseClass
{
private decimal _Result;
public override decimal Result
{
get { return _Result; }
// This setter throws a build error because of a change of access modifiers.
//set { _Result = value; }
}
}
我不想使用 setter 在 BaseClass 中添加成员变量,因为我不希望能够从 BaseClass 或从 base 派生的其他类设置属性。
public class BaseClass
{
private BaseClass _Parent;
protected Decimal _Result; // This could result in a lot of unnecessary members in BaseClass.
public virtual decimal Result {
get { return _Result; }
// Empty setter ahead :) This does nothing.
// I could also throw an exception here but then issues would not be found until runtime
// and could cause confusion in the future with new developers etc.
set { }
}
}
public class DerivedClass : BaseClass
{
public override decimal Result
{
get { return base.Result; }
set { base._Result = value; }
}
}
其他建议?
您可以使用 'new' 关键字,但这将替换属性,您想要的内容无法通过覆盖实现。
public class BaseClass
{
private BaseClass _Parent;
public virtual decimal Result
{
get { return ((_Parent != null) ? _Parent.Result : -1); }
}
}
public class DerivedClass : BaseClass
{
private decimal _Result;
public new decimal Result
{
get { return _Result; }
set { _Result = value; }
}
}
如果可以在 BaseClass 中添加受保护的 setter,则可以在 DerivedClass 中使用 new 关键字:
public class BaseClass // ReadOnlyClass
{
public int Value { get; protected set; }
}
public class DerivedClass : BaseClass
{
public new int Value
{
get => base.Value;
set => base.Value = value;
}
}
我最终改变了我处理它的方式并将集合留在基类中,但是我没有让基类 getter / setter 什么都不做,而是抛出了 NotImplemented / NotSupported 异常。
public class BaseClass
{
private BaseClass _Parent;
public virtual decimal Result
{
get
{
if (Parent == null)
throw new NotImplementedException("Result property not valid");
return Parent.Result;
}
set
{
throw new NotSupportedException("Result property cannot be set here");
}
}
}
public class DerivedClass : BaseClass
{
private decimal _Result;
public override decimal Result
{
get { return _Result; }
set { _Result = value; }
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.