C#覆盖子类中的属性

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 } 

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

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

这个对我有用。

测试代码:

 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(); } 

这正是可以“覆盖”的框架属性的原因,采用布尔参数(在它的表面上)似乎毫无意义。 以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;} } 

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

我不明白麻烦是什么。 你发布的代码在我的测试中完成了预期的事情(至少,你期望它做什么):也就是说, StyleString属性没有ExternallyVisible属性。 这是我的测试代码:

 [AttributeUsage(AttributeTargets.Property)] public class ExternallyVisible : Attribute { } 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 } class Program { static void Main() { MyWebControl myctrl = new MyWebControl(); SmarterWebControl smartctrl = new SmarterWebControl(); MemberInfo info = typeof(SmarterWebControl); PropertyInfo[] props = (typeof(SmarterWebControl)).GetProperties(); Console.WriteLine("{0} properties", props.Length); foreach (var prop in props) { Console.WriteLine(prop.Name); foreach (var attr in prop.GetCustomAttributes(true)) { Console.WriteLine(" " + attr); } } Console.ReadLine(); } } 

在.NET 4.0中,我得到了这个输出:

 2 properties CssName sotesto.ExternallyVisible StyleString 

换句话说,该属性不适用于StyleString属性。

您可以inheritance该属性并添加一个属性来控制是否触发attrbiute代码。

那么你可以覆盖inheritance类的属性行为?

所以你会使用(如果你在构造函数中添加了一个参数)

 [ExternallyVisible(false)] [ExternallyVisible(Enabled = false)] 

我在atrtibute类中使用了启用的属性