C# 为什么我重新实现的方法保留了基类&x27;属性
我有两个类,C# 为什么我重新实现的方法保留了基类&x27;属性,c#,asp.net-mvc,C#,Asp.net Mvc,我有两个类,RichString和RequiredRichString。在RequiredRichString中,我正在用'new'关键字实现值属性。如果我在RequiredRichString上反映Value上的属性,我只得到Required,但是在多次测试POST标记之后,allowtml仍然生效 public class RichString { [AllowHtml] public string Value { get; set; } } public class Re
RichString
和RequiredRichString
。在RequiredRichString
中,我正在用'new'关键字实现值
属性。如果我在RequiredRichString
上反映Value
上的属性,我只得到Required
,但是在多次测试POST标记之后,allowtml
仍然生效
public class RichString
{
[AllowHtml]
public string Value { get; set; }
}
public class RequiredRichString : RichString
{
[Required]
new public string Value { get; set; }
}
简而言之:如果设置了标志,为什么ASP.NET在使用
new
重新实现Value
属性时仍然确认AllowHtml
属性
[AttributeUsage(Inherited=true)]
然后该属性将被继承
但是您可以根据需要将属性子类化,即在基类中为MyAttribute(Enabled=true)
,在新实现中为MyAttribute(Enabled=false)
。例如
[AttributeUsage(Inherited=true, AllowMultiple=true, Inherited=true)]
public class MyAttribute : Attribute
{
public bool Enabled { get; set; }
public MyAttribute() { }
public void SomethingTheAttributeDoes()
{
if (this.Enabled) this._DoIt)();
}
}
public class MyObject
{
[MyAttribute(Enabled = true)]
public double SizeOfIndexFinger { get; set; }
}
public class ExtendedObject : MyObject
{
[MyAttribute(Enabled = false)]
public new double SizeOfIndexFinger { get; set; }
}
注意这个答案:-似乎您可以通过使用方法重写而不是隐藏来实现您想要的
我可以理解为什么您会对new
属性不这么认为,但我的理解是new
是提供一个新的实现,通常是以新的存储机制(例如一个新的备份字段)的形式,而不是更改子类的可见接口Inherited=true
承诺子类将继承属性
。这是有道理的,或者至少可以说,只有一个替代的属性
才能打破这一承诺