Combining multiple attributes in C#

二次信任 提交于 2019-12-18 04:32:00

问题


Is there a functional difference between the following syntax...

[Foo, Bar]
public class Baz {}

...and this syntax?

[Foo]
[Bar]
public class Baz {}

Assuming each produces identical results when compiled, which is the preferred form?


回答1:


There is no functional difference. It's a question of convenience and style.

Most often, I tend to see attributes on their own lines as a way to keep them separate and easy to read. It's also nice to be able to use the line comment // to remove attributes individually.

[A]
[B]
//[C] disabled
public class Foo {} 



回答2:


From a readability standpoint separate attributes are preferred.

Think about the case where you are passing some type of parameter

 [Foo(typeof(int)), Bar(typeof(decimal), MessageTemplate="Bar")]

versus

 [Foo(typeof(int))]
 [Bar(typeof(decimal), MessageTemplate="Bar")]

I would also argue, if you could combine them into one, they should be one tag.




回答3:


I typically stack attributes. But I also mainly use these with WCF where the parameter list can get pretty big.

[OperationContract()]
[WebGet(...)]
string MyMethod(string input);


来源:https://stackoverflow.com/questions/2546924/combining-multiple-attributes-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!