C# 是否更改派生类中属性的值?
我在基类中有一个用属性标记的属性,我想更改每个派生类中的一些属性。最好的方法是什么 据我所知,我必须在基类中将属性定义为抽象属性,并重写每个基类中的属性,并重新定义所有属性。这似乎真的是多余的,我对此并不着迷,因为我必须在每个派生类中重复公共属性C# 是否更改派生类中属性的值?,c#,inheritance,attributes,C#,Inheritance,Attributes,我在基类中有一个用属性标记的属性,我想更改每个派生类中的一些属性。最好的方法是什么 据我所知,我必须在基类中将属性定义为抽象属性,并重写每个基类中的属性,并重新定义所有属性。这似乎真的是多余的,我对此并不着迷,因为我必须在每个派生类中重复公共属性 这是我试图做的一个简单的例子。我想更改派生类中的MyAttribute,但保持属性上的所有其他属性相同,并在一个位置定义(即,我不想多次重新定义xmlement)。这可能吗?还是有更好的方法?还是我在这里完全滥用了属性 using System;
这是我试图做的一个简单的例子。我想更改派生类中的
MyAttribute
,但保持属性上的所有其他属性相同,并在一个位置定义(即,我不想多次重新定义xmlement
)。这可能吗?还是有更好的方法?还是我在这里完全滥用了属性
using System;
using System.Xml;
using System.Xml.Serialization;
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class MyAttribute : System.Attribute
{
public MyAttribute() {}
public string A { get; set; }
public string B { get; set; }
}
public abstract class BaseClass
{
public BaseClass() {}
[XmlElement("some_property")]
[MyAttribute(A = "Value1", B = "Value2")]
public string SomeProperty { get; set; }
}
public class FirstDerivedClass : BaseClass
{
//I want to change value B to something else
//in the MyAttribute attribute on property SomeProperty
}
public class SecondDerivedClass : BaseClass
{
//I want to change value B to yet another value
//in the MyAttribute attribute on property SomeProperty
}
您可以使用该方法返回所有继承级别上的所有属性,或者只返回实现的类。不幸的是,这不允许您重写“AllowMultiple=false”属性。您可能会创建一个方法,该方法调用GetCustomAttribute两次,一次使用继承值,一次不使用继承值。然后,您可以将非继承值优先于继承值。如果需要,我可以稍后发布一个示例。“或者我完全误用了这里的属性吗?”-从这一点来看,这就是它的感觉。你用你的实际属性做什么?在一个小项目中,我试验了反射,我用属性生成带有错误消息和类似信息的html表单。再说一次,这可能不是属性的最佳使用,但我学到了一些新东西。