访问自定义属性的值

RCP*_*CPT 22 c# attributes

我有这个自定义属性:

[AttributeUsage(AttributeTargets.Method, AllowMultiple=false, Inherited = true)]
class MethodTestingAttibute : Attribute
{   
    public string Value{ get; private set; }
    public MethodTestingAttibute (string value)
    {
        this.Value= value;

    }
}
Run Code Online (Sandbox Code Playgroud)

要像这样使用:

[MethodTestingAttibute("2")]
public int m1() {return 3; }
Run Code Online (Sandbox Code Playgroud)

而我的理念是采用MethodTestingAttibute的"2"值

object result = method.Invoke(obj, new Type[] {}); // here i get the return
Run Code Online (Sandbox Code Playgroud)

现在我想将此结果与Method TestingAttibute的值进行比较.我怎么能这样做?我试图走上这条路,但没有成功:method.GetCustomAttributes(typeof(MethodTestAttibute),true)[0] ...

什么是正确访问Custoum属性的字段?

age*_*t-j 28

var attribute =
   (MethodTestingAttibute)
   typeof (Vehicles)
      .GetMethod("m1")
      .GetCustomAttributes(typeof (MethodTestingAttibute), false).First();
Console.WriteLine(attribute.Value);
Run Code Online (Sandbox Code Playgroud)


Joa*_*tos 5

使用我的自定义属性:

[AttributeUsage(AttributeTargets.Method)]
public class AttributeCustom : Attribute
{
    public string MyPropertyAttribute { get; private set; }

    public AttributeCustom(string myproperty)
    {
        this.MyPropertyAttribute = myproperty;
    }
}
Run Code Online (Sandbox Code Playgroud)

我创建了一个方法来获取属性及其值:

public static AttributeCustom GetAttributeCustom<T>(string method) where T : class
{
    try
    {
        return ((AttributeCustom)typeof(T).GetMethod(method).GetCustomAttributes(typeof(AttributeCustom), false).FirstOrDefault());
    }
    catch(SystemException)
    {
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

使用示例类(必须不是静态的,因为 T 是通用的)

public class MyClass
{
    [AttributeCustom("value test attribute")])
    public void MyMethod() 
    {
        //...
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

var customAttribute = GetAttributeCustom<MyClass>("MyMethod");
if (customAttribute != null)
{
    Console.WriteLine(customAttribute.MyPropertyAttribute);
}
Run Code Online (Sandbox Code Playgroud)