简体   繁体   English

C#-使用属性的替代方法

[英]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 ? 喜欢xml文件?

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. 某些情况下 ,属性实际上可以在运行时添加-但它们仅在TypeDescriptor下显示(这是大多数UI数据绑定使用的功能),而不是原始反射。

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. 您也可以使用properties做一些技巧,但这很多种模式……

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 文件1

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

file 2 文件2

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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