我需要获取自定义属性的值。我的要求几乎与此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。
Microsoft.FxCop.Sdk.AttributeNode
不能被转换到一个正常的System.Attribute
,System.Reflection.CustomAttributeData
或其他任何东西,我试过了。最后,我可以使用以下函数获得所需的值:
public Microsoft.FxCop.Sdk.Expression GetPositionalArgument(int position)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句