且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

访问自定义属性的值

更新时间:2022-12-11 09:38:05

  var属性=
   (MethodTestingAttibute)
   typeof运算(车辆)
      .GetMethod(M1)
      .GetCustomAttributes(typeof运算(MethodTestingAttibute),假的)。首先();
Console.WriteLine(attribute.Value);

Ive got this Custom Attribute:

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

    }
}

To be used like this:

    [MethodTestingAttibute("2")]
    public int m1() {return 3; }

And my dificulty is to take the Value of "2" of the MethodTestingAttibute

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

Now i want to compare this result to the Value of the Method TestingAttibute. How i can do that? Im trying to go up to this road but without success: method.GetCustomAttributes(typeof(MethodTestAttibute), true)[0]...

What is the properly to get access to the field of the Custoum Attribute?

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