How to assign a property to an attribute

I would like to assign a property string below the attribute.

[ExtractKeyAttribute(**"Extraction"**)]

public class Extract
{
  ....
}

so fetching is my line, but I don't want hard code to be there. Any suggestions for a more effective appointment

+5
source share
3 answers

You cannot do this.

Attribute values ​​must be constant expressions. Values ​​are baked into compiled code. If you do not want to use a constant expression, you cannot use the attribute ... and you probably shouldn't. This may mean that you use attributes when you should use a different approach.

You might want to read Eric Lippert's post on properties versus attributes .

, . :

[ExtractKey(ExtractionKeys.Extraction)]
...


public static class ExtractionKeys
{
    public const string Extraction = "Extraction";
}

... .

+13

, () . readonly? , ? , . U .

...

static class MyClass
{
     public string MyValue {get;}
}

:

static class MyClass
{
     public const string MyValue= "MyValue";
}

:

[ExtractKey(MyClass.MyValue)]
0

If you want to change the property of your attribute at runtime, you can do this with this code:

ExtractKeyAttribute myAttribute = typeof(Extract).GetCustomAttributes(typeof(ExtractKeyAttribute), false)[0] as ExtractKeyAttribute;
myAttribute.MyValue = "MyRunTimeValue";
0
source

All Articles