Question

Is there a way around to pass non-constant complex or primitive values to an attribute?

public class SomeClass
{
     private SomeOtherClass _someOtherClass = new SomeOtherClass();
     private int _somePrimitiveVariable = CalculateSomeValue();

     [MyAttribute(InputValue = _someOtherClass)
     public void MyMethod()
     {
         //Some stuff
     }
     //Or can it be like this?
     [MyAttribute(InputValue = _somePrimitiveVariable)
     public void MyMethod()
     {
         //Some stuff
     }
}
Était-ce utile?

La solution

Attributes are resolved at compile time, so the comments saying "no" are mostly correct.

However, if you can't rework your design, there are limited workarounds. If this is a universal property you wish to set (that will apply to every user of the attribute), your best bet might be having an initializer method in your code call a configuration method on the attribute. This would look vaguely similar to Can C# Attributes access the Target Class?. Ugly, but might work in specific circumstances.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top