Composite Attribute

2019-06-24 05:31发布

问题:

Is there any way of making a composite attribute in C# to provide equivalent metadata at compile time?

E.g, change:

[ClassInterface(ClassInterfaceType.AutoDual)]
[ProgId("MyProgId")]
[MyMefExport("MyProgId")]
public class MyClass
{
}

To:

[MyCompositeAttribute("MyProgId")]
public class MyClass
{
}

回答1:

Attributes in and of themselves are meaningless. It is the code that enumerates the attributes attached to a class that may change its operation.

If you control the code that understands the attribute, you could create a composite attribute and act as though multiple separate attributes were applied.

That being said, I doubt you control ProgId nor the C# compiler that interprets it...



回答2:

Say you had the following code to read your custom attribute:

var attrs = typeof(MyClass).GetCustomAttributes(typeof(MyCompositeAttribute) ,false);

Any code that relied on say:

var attrs = typeof(MyClass).GetCustomAttributes(typeof(ProgId) ,false);

will fail to return that attribute.