继承字段的特性重写:子类能否为父类属性新增特性并保留原有特性?
Absolutely, this is totally doable in C#—but the approach depends on whether the base class attributes are designed to be inherited, and how you implement the subclass property. Let’s break this down step by step:
1. Check if Base Class Attributes Support Inheritance
By default, most custom attributes don’t get inherited by subclass properties unless the attribute itself is marked with [AttributeUsage(Inherited = true)].
For example, if your Attribute1 is defined like this:
[AttributeUsage(AttributeTargets.Property, Inherited = true)] public class Attribute1 : Attribute { }
Then any subclass that overrides Property1 will automatically inherit Attribute1 and Attribute2 (assuming those also have Inherited = true). You can just add your new attributes directly:
public class MySubClass : MyBaseClass { // Inherits [Attribute1] and [Attribute2] from base, plus adds [NewAttribute] [NewAttribute] public override string Property1 { get; set; } }
2. If Attributes Don’t Support Inheritance
If the base class attributes don’t have Inherited = true (which is the default for custom attributes), overriding the property won’t bring those attributes along. To keep them, you’ll need to re-declare the base attributes alongside your new ones in the subclass:
public class MySubClass : MyBaseClass { // Re-declare base attributes + add new ones [Attribute1] [Attribute2] [NewAttribute1] public override string Property1 { get; set; } [Attribute3] [Attribute4] [NewAttribute2] public override string Property2 { get; set; } }
This ensures both the original base attributes and your new ones are applied to the subclass property.
3. Important Notes About Reflection
If you’re using reflection to read attributes later, make sure to use the overload of GetCustomAttributes that includes inherited attributes:
var property = typeof(MySubClass).GetProperty("Property1"); // Pass 'true' to include inherited attributes var allAttributes = property.GetCustomAttributes(true);
Using GetCustomAttributes(false) will only return attributes directly declared on the subclass property, excluding inherited ones.
4. Avoid Using new to Hide the Base Property
Resist the urge to use the new keyword to "replace" the base property (e.g., public new string Property1 { get; set; }). This creates a completely new property that has no connection to the base class’s property—so you’ll lose all base attributes entirely, and it can lead to unexpected behavior when working with polymorphism.
内容的提问来源于stack exchange,提问作者Novice Student

