R
R
Ruslan2016-06-03 13:58:15
C++ / C#
Ruslan, 2016-06-03 13:58:15

Getting method attributes when using Func?

Hello.
There is a c# code that does not work as we would like :)

public class myclass
{
        public class MyAttribute : Attribute { }

        [MyAttribute]
        public string MyMethod()
        {
            return "";
        }

        public void MainMethod()
        {
            Func<string> m = MyMethod;
            Type t = m.GetType();
            object[] attrs=t.GetCustomAttributes(typeof(MyAttribute), true);
        }
}

The last row of the MainMethod method has 0 elements in the attrs array, i.e. get method attribute MyMethod fails.
The question is how to get to the attribute of the MyMethod method from the MainMethod method?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Kronic, 2016-06-03
@Razbezhkin

public void MainMethod()
{
  Func<string> method = MyMethod;
  var methodName = method.GetMethodInfo().Name;

  var type = method.Target.GetType();

  var attrs = type.GetMethod(methodName).GetCustomAttributes(typeof(MyAttribute), true);
}

And below was the original version without using Func
public void MainMethod()
{
  var method = typeof(myclass).GetMethod("MyMethod");
  var attrs = method.GetCustomAttributes(typeof(MyAttribute), true);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question