问题
This doesn't seem possible, but I'll ask anyway... Is it possible in C# to apply a single attribute to multiple fields at once?
public class MyClass {
[SomeAttribute]
public int m_nVar1;
[SomeAttribute]
public int m_nVar2;
public int m_nVar3;
}
Is there a short-hand method to put the "SomeAttribute" on m_Var1 & m_Var2, but not on m_nVar3? Currently, we are placing the attributes before each field, but it would be nice to put all the fields using a attribute inside a block.
回答1:
Yes, it's possible:
[SomeAttribute]
public int m_nVar1, m_nVar2;
(but obviously only if the types are the same)
回答2:
This could work?, but might end up being pretty tedious
public class CustomClass
{
[CustomAttribute]
public dynamic value { get; set; }
}
public class MyClass
{
public CustomClass m_nVar1, var2, var3;
public MyClass()
{
m_nVar1.value = (int)m_nVar1.value;
var2.value = (string)var2.value;
}
}
来源:https://stackoverflow.com/questions/10725998/can-you-apply-a-attribute-to-multiple-fields-in-c