I want to "read" the parameters of attributes whether they are attached to a class or to a method, or want to get back the attribute object of a particular class or method. This seems to be not available for all cases.
While I was trying to implement it, i.e.
??1. Read parameters of an attribute, attached to a class. How? (see Question 1)
Parameters are the constructor parameters of the attribute, e.g.
public MyOwnAttribute(params object[] p)
.
??2. Get attibute object's properties, attached to a method. How? (see Question 2)
In the example attribute MyOwnAttribute
, there are MyProperty1
and MyProperty2
defined. So if you apply it to
[MyOwnAttribute("World", "2")]
public void MyMethod2() {...}
,
how can I read them (the constructor assigns "World"
to MyProperty1
and "2"
to MyProperty1
)?
??3. Read parameters of an attribute, attached to a method. Solved.
Example:
MyOwnAttribute.GetMethodAttributeValues<clsA>(nameof(clsA.MyMethod2))
??4. Get attribute object's properties, attached to a class. Solved.
Example: MyOwnAttribute.GetClassAttributes(typeof(clsA)).MyProperty1
I noticed that I couldn't implement it for all 4 cases, I couldn't implement it for cases 1. and 4. The code I wrote for cases 2. and 3. is working fine (I removed it since you now have Tobias' answer for all 4 cases). The SO sidebar shows some interesting links ("Related": Link 1, Link 2, Link 3), but still I couldn't put the missing pieces together.
Consider the following custom attribute:
public class MyOwnAttribute : Attribute
{
public string MyProperty1 { get; set; }
public string MyProperty2 { get; set; }
// simple case, to make explaining it easier
public MyOwnAttribute(string p1 = null, string p2 = null)
{
MyProperty1 = p1?.ToString();
MyProperty2 = p2?.ToString();
}
}
Or I could have the properties defined like:
public string[] MyProperties { get; set; }
// allows any number of properties in constructor
public MyOwnAttribute(params object[] p)
{
MyProperties = p.Select(s => s.ToString()).ToArray();
}
But I couldn't figure out how you could implement this:
Question 1: How can I access the list of attribte's parameter values attached to a class?
(from the attribute's constructor, like implemented for the methods)
Example:
var classAttribParamValues = MyOwnAttribute.GetClassAttributeValues(typeof(clsA));
string.Join(' ', classAttribParamValues.Select(s => s ?? "")).Dump();
Question 2: How can I access attribute's properties attached to a method?
(like implemented for the class)
Example:
var methodInfo = MyOwnAttribute.GetMethodAttributes<clsA>(nameof(clsA.MyMethod2));
methodInfo.MyProperty1.Dump();
Does anyone have an idea how that can be done? Many thanks in advance.
See Question&Answers more detail:
os