我需要获取自定义属性的值。我的要求与此MSDN link中给出的示例几乎相似(转载如下)。
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。
答案 0 :(得分:2)
Microsoft.FxCop.Sdk.AttributeNode
无法投放到正常的System.Attribute
,System.Reflection.CustomAttributeData
或我尝试过的任何其他内容。最后,我可以使用以下函数获得我想要的值:
public Microsoft.FxCop.Sdk.Expression GetPositionalArgument(int position)
答案 1 :(得分:1)
如果你不能使用强类型,你必须使用反射。
一个简单的例子:
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