获取自定义属性值
本文关键字:自定义属性 获取 | 更新日期: 2023-09-27 18:10:36
我需要获得自定义属性的值。我的要求几乎类似于这个MSDN链接中给出的示例(下面转载)。
using System;
using System.Reflection;
// An enumeration of animals. Start at 1 (0 = uninitialized).
public enum Animal {
// Pets.
Dog = 1,
Cat,
Bird,
}
// A custom attribute to allow a target to have a pet.
public class AnimalTypeAttribute : Attribute {
// The constructor is called when the attribute is set.
public AnimalTypeAttribute(Animal pet) {
thePet = pet;
}
// Keep a variable internally ...
protected Animal thePet;
// .. and show a copy to the outside world.
public Animal Pet {
get { return thePet; }
set { thePet = value; }
}
}
// A test class where each method has its own pet.
class AnimalTypeTestClass {
[AnimalType(Animal.Dog)]
public void DogMethod() {}
[AnimalType(Animal.Cat)]
public void CatMethod() {}
[AnimalType(Animal.Bird)]
public void BirdMethod() {}
}
class DemoClass {
static void Main(string[] args) {
AnimalTypeTestClass testClass = new AnimalTypeTestClass();
Type type = testClass.GetType();
// Iterate through all the methods of the class.
foreach(MethodInfo mInfo in type.GetMethods()) {
// Iterate through all the Attributes for each method.
foreach (Attribute attr in
Attribute.GetCustomAttributes(mInfo)) {
// Check for the AnimalType attribute.
if (attr.GetType() == typeof(AnimalTypeAttribute))
Console.WriteLine(
"Method {0} has a pet {1} attribute.",
mInfo.Name, ((AnimalTypeAttribute)attr).Pet);
}
}
}
}
/*
* Output:
* Method DogMethod has a pet Dog attribute.
* Method CatMethod has a pet Cat attribute.
* Method BirdMethod has a pet Bird attribute.
*/
在上面的代码中,自定义属性被强制转换为它的类型(AnimalTypeAttribute
),然后得到它的值。我有一个类似的场景,但是我没有自定义属性的引用,因此不能强制转换它以获得它的值。我能够获得属性节点,但是,我无法找到它的最终值。在上面的例子中,属性是"AnimalTypeAttribute",它的值是"Dog"、"Cat"、"Bird"等。我能够找到属性节点"AnimalTypeAttribute",我现在需要的是值"狗","猫"等。有办法做到这一点吗?
附加信息(不确定它是否改变了任何东西):我正在创建一个自定义的FxCop规则,我的节点类型是Microsoft.FxCop.Sdk.AttributeNode
。
TIA。
如果不能使用强类型,则必须使用反射。
一个简单的例子:
Attribute[] attributes = new Attribute[]
{
new AnimalTypeAttribute(Animal.Dog),
new AnimalTypeAttribute(Animal.Cat),
new AnimalTypeAttribute(Animal.Bird)
};
foreach (var attribute in attributes)
{
var type = attribute.GetType();
var petProperty = type.GetProperty("Pet");
var petValue = petProperty.GetValue(attribute);
Console.WriteLine("Pet: {0}", petValue);
}
// Output:
// Pet: Dog
// Pet: Cat
// Pet: Bird
Microsoft.FxCop.Sdk.AttributeNode
不能转换为正常的System.Attribute
, System.Reflection.CustomAttributeData
或我尝试过的任何其他内容。最后,我可以使用以下函数获得我正在寻找的值:
public Microsoft.FxCop.Sdk.Expression GetPositionalArgument(int position)