Applying the C # attribute to many fields

Suppose I have a minimal C # class that looks like this:

class Thing { private float a, b, c, d; (...) } 

Is there a way I can apply an attribute to all four fields without writing it four times? If I put [SomeAttribute] in front of private , it seems to apply only to a .

+4
source share
3 answers

Yes, it is possible:

 [SomeAttribute] public int m_nVar1, m_nVar2; 

(but, obviously, only if the types are the same)

LINK

Example:

 [ContextStatic] private float a, b, c, d; 
+3
source
 class Thing { [SomeAttribute] public float a, b, c, d; } 

The above that you proposed will work the way you expect it to work. You can check this out:

 [AttributeUsage(AttributeTargets.Field)] sealed class SomeAttribute: Attribute { public SomeAttribute() { } } class Program { static void Main(string[] args) { var t = typeof(Thing); var attrs = from f in t.GetFields() from a in f.GetCustomAttributes() select new { Name = f.Name, Attribute = a.GetType() }; foreach (var a in attrs) Console.WriteLine(a.Name + ": " + a.Attribute); Console.ReadLine(); } } 

He prints:

  a: SomeAttribute
 b: SomeAttribute
 c: SomeAttribute
 d: SomeAttribute
+4
source

I do not think that you can achieve this using a visual studio.

The most annoying way I can think of is to use MultiEdit , where you can place multiple cursors and only write the attribute once.

0
source

All Articles