Can you apply a attribute to multiple fields in C#?

☆樱花仙子☆ 提交于 2019-12-01 15:25:07

问题


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

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