Combining multiple attributes in C#

2019-01-26 02:41发布

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?

3条回答
贪生不怕死
2楼-- · 2019-01-26 03:19

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楼-- · 2019-01-26 03:26

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);
查看更多
够拽才男人
4楼-- · 2019-01-26 03:29

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 {} 
查看更多
登录 后发表回答