Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
995 views
in Technique[技术] by (71.8m points)

.net - Can you get merged attributes for a class in C#?

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.

i.e. [Another("Bob")] and [My(16)]

Is it possible for the attributes to be merged? So I would end up with two attributes of [My(16, "Male")] and [Another("Bob")]

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
{
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

(In theory a post processor that re-wrote the MSIL could do this.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...