简体   繁体   中英

C# - Alternative way to use attribute

Let say I got the following :

public class A {
     [MyAttribute]
     public void Test() {}
}

I don't like the behavior of adding an attribute to prefix a method or a class with []. I think that make the code less readable.

I find that a better approach can be something like :

AddAttribute(A, Test, MyAttribute);

Is there a way of doing something like that ?

Because that is some kind of adding attribute at runtime...

Or is there other way to use attribute ? Like xml files ?

Attributes cannot be added at runtime, they are embedded in the metadata of the assembly. You can, however, add attributes by using an external tool during build that modifies your source code before compiling.

No, there are no generic solution for replacing attributes.

However, there are other ways to implement stuff that are provided by attributes. It really depends on the framework that you are using.

It depends on the context; for some scenarios , attributes actually can be added at runtime - but they only show under TypeDescriptor (which is what most UI data-binding uses), and not raw reflection.

For example, for annotating a type :

TypeDescriptor.AddAttributes(typeof(Foo),
    new TypeConverterAttribute(typeof(ExpandableObjectConverter)));

to replace the type-converter for a type at runtime .

You can also do some tricks with properties , but it is a lot mode... fiddly.

For the general case; just use code attributes. There is nothing inherently unreadable about attributes, and their location serves to highligh that they are metadata - about the type/method, but not really part of the type/method itself.


The following is for discussion only; I wouldn't do this just because you don't like the look of it (although I have done something like this to help annotate machine-generated code):

file 1

[Description("evil evil evil")]
partial class Foo {
    [Description("don't do this")]
    partial void Bar();
}

file 2

partial class Foo {
    partial void Bar() {
        Console.WriteLine("I can only be called from inside the type; "
           + "I can't be public");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM