假设我有以下一组类,是否可以合并 DerivedClass 的属性?目前,如果我使用传递 true 的 GetType().GetCustomAttributes() 方法进行继承,它将采用继承结构中的最高属性.
Say I have the following set of classes, is it possible for the attributes of DerivedClass to be merged? Currently if I use the GetType().GetCustomAttributes()method passing in true for inheritance it takes the highest attributes in the inheritance structure.
即[另一个(鲍勃")]和[我的(16)]
i.e. [Another("Bob")] and [My(16)]
属性可以合并吗?所以我最终会得到两个属性 [My(16, "Male")] 和 [Another("Bob")]
Is it possible for the attributes to be merged? So I would end up with two attributes of [My(16, "Male")] and [Another("Bob")]
我并不是说我会指定一个属性为 [My(16, "Male")],而是我会返回一个年龄为 16 岁且性别为男性的属性.
I don't mean to say that I would specify an attribute of [My(16, "Male")] but rather I would be returned an attribute with an Age of 16 and a Gender of Male.
public class MyAttribute : Attribute
{
public MyAttribute(int age)
{
Age = age;
}
public MyAttribute(int age, string gender)
{
Age = age;
Gender = gender;
}
public int Age { get; set; }
public string Gender { get; set; }
}
public class AnotherAttribute : Attribute
{
public AnotherAttribute(string name)
{
Name = name;
}
public string Name { get; set; }
}
[My(12, "Male")]
[Another("Bob")]
public class BaseClass
{
}
[My(16)]
public class DerivedClass : BaseClass
{
}
您可以在一个实体上拥有同一属性的多个实例(这是应用于您的属性的 AttributeUsageAttribute
上的一个选项).当你获取一个类型的属性时,你可以获取应用到继承链的所有属性.
You can have multiple instances of the same attribute on an entity (this is an option on the AttributeUsageAttribute
applied to your attribute). When you get attributes on a type, you can get all the attributes applied to the inheritance chain.
但是,标准工具中没有任何东西会采用两个属性实例并生成一个.
However there is nothing in the standard tools that will take two attribute instances and make one.
(理论上,重写 MSIL 的后处理器可以做到这一点.)
(In theory a post processor that re-wrote the MSIL could do this.)
这篇关于你能在 C# 中获得一个类的合并属性吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!