C#覆盖子类中的属性

Mik*_*ord 22 c# attributes

public class MyWebControl {

    [ExternallyVisible]
    public string StyleString {get;set;}

}

public class SmarterWebControl : MyWebControl {

    [ExternallyVisible]
    public string CssName{get;set;}

    new public string StyleString {get;set;} //Doesn't work

}
Run Code Online (Sandbox Code Playgroud)

是否可以删除子类中的属性?我确实希望该属性被其他子类继承,而不是这个.

编辑:哎呀,看起来我忘了编译或者其他东西,因为上面发布的代码确实有用!

Jam*_*iec 20

这正是可以"覆盖"的框架属性的原因,采用布尔参数(在它的表面上)似乎毫无意义.就拿BrowsableAttribute例如; 根据名称判断布尔参数似乎已过时,但请举例:

class SomeComponent
{
  [Browsable(true)]
  public virtual string SomeInfo{get;set;}
}

class SomeOtherComponent : SomeComponent
{
  [Browsable(false)]  // this property should not be browsable any more
  public override string SomeInfo{get;set;}
}
Run Code Online (Sandbox Code Playgroud)

所以,为了回答你的问题,你可以让你的ExternallyVisible属性采用布尔参数,以指示它是否实际上是外部可见的,当你继承时,你可以改为false - 就像BrowsableAttribute.


Chr*_*tin 6

这个对我有用.

测试代码:

public static void Main()
{
    var attribute = GetAttribute(typeof (MyWebControl), "StyleString", false);
    Debug.Assert(attribute != null);

    attribute = GetAttribute(typeof(SmarterWebControl), "StyleString", false);
    Debug.Assert(attribute == null);

    attribute = GetAttribute(typeof(SmarterWebControl), "StyleString", true);
    Debug.Assert(attribute == null);
}

private static ExternallyVisibleAttribute GetAttribute(Type type, string propertyName, bool inherit)
{
    PropertyInfo property = type.GetProperties().Where(p=>p.Name.Equals(propertyName, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();

    var list = property.GetCustomAttributes(typeof(ExternallyVisibleAttribute), inherit).Select(o => (ExternallyVisibleAttribute)o);

    return list.FirstOrDefault();
}
Run Code Online (Sandbox Code Playgroud)