为什么我重新实现的方法保留了基类的属性?

时间:2015-07-04 04:03:29

标签: c# asp.net-mvc

我有两个班级,RichStringRequiredRichString。在RequiredRichString中,我正在使用'new'关键字重新实现Value属性。如果我在Value RequiredRichString上反映了Required上的属性,我只会获得AllowHtml,但在多次测试发布标记后,public class RichString { [AllowHtml] public string Value { get; set; } } public class RequiredRichString : RichString { [Required] new public string Value { get; set; } } 仍然有效。

AllowHtml

简而言之:当我使用Value重新实现new属性时,为什么ASP.NET仍然会确认while ( $row = mysql_fetch_assoc( $result ) ) { echo $prefix . " {\n"; echo ' "category": "' . $row['tstamp'] . '",' . "\n"; echo ' "value": ' . ( (float) $row['temp'] ) . "\n"; echo " }"; $prefix = ",\n"; } echo "\n]"; 属性?

1 个答案:

答案 0 :(得分:1)

如果您设置了标志:

[AttributeUsage(Inherited=true)]

然后该属性将被继承。

但您可以将Attribute子类化为您的需求,即基类中的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; }
}

请注意这个答案:How to hide an inherited property in a class without modifying the inherited class (base class)? - 似乎你可以通过使用方法覆盖而不是隐藏来实现你想要的目标。

我可以理解为什么你会考虑使用new属性,但我的理解是new是关于提供新的实现,通常是以新存储机制(例如新的支持字段),而不是更改子类的可见接口Inherited=true是子类将继承Attribute的承诺。这是有道理的,或者至少可以说只有取代Attribute应该能够打破这一承诺。