Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何查找lambda表达式调用的方法的属性?_C#_Reflection_Lambda_Attributes - Fatal编程技术网

C# 如何查找lambda表达式调用的方法的属性?

C# 如何查找lambda表达式调用的方法的属性?,c#,reflection,lambda,attributes,C#,Reflection,Lambda,Attributes,出于各种原因,我需要运行如下代码: public class MethodRunner { public T RunMethod<T>(Func<T> method) { method.Invoke(); } } public class MyClass { [MyAttribute("somevalue")] public string SayHello(string message) {

出于各种原因,我需要运行如下代码:

public class MethodRunner {
     public T RunMethod<T>(Func<T> method) {
          method.Invoke();
     }
}
public class MyClass {
     [MyAttribute("somevalue")]
     public string SayHello(string message) {
         Console.WriteLine(message);
         return message;
     }
}
然后,我可以通过编写

var runner = new MethodRunner();
var myClass = new MyClass();

runner.RunMethod(() => myClass.SayHello("hello!"));

我想做的是,在
MethodRunner.RunMethod
的主体中,使用反射查看
MyClass.SayHello
上的
MyAttribute
类的参数。然而,我不知道怎么去那里。我所能看到的使用反射的是lambda表达式本身,而不是它的内容。

如果您能够将
Func
改为
表达式,这很容易

以下是一个可能的示例:

public class MethodRunner {
     public T RunMethod<T>(Expression<Func<T>> method) {
          var body = method.Body as MethodCallExpression;
          if (body == null)
              throw new NotSupportedException();

           var attributes = body.Method.GetCustomAttributes(false);

           // Do something with Attributes

           return expression.Compile().Invoke();
     }
}
公共类MethodRunner{
公共runt方法(表达式方法){
var body=method.body作为MethodCallExpression;
if(body==null)
抛出新的NotSupportedException();
var attributes=body.Method.GetCustomAttributes(false);
//用属性做一些事情
返回表达式.Compile().Invoke();
}
}

仅将
Func
()=>
一起使用的困难在于编译器将生成实际的方法。就我所知,您无法从方法中获取代码的“行”。解决这个问题的一种方法是使用
RunMethod(myClass.SayHello)
而不是
RunMethod(()=>myClass.SayHello)

简单回答:你不能(很容易做到)。如果你能说出你想解决什么问题,答案就很简单了。这是一个lambda表达式(是的,在
d
之前是b
,不仅仅是lamba,就像你拼了两遍一样)。相信,你必须用表达式而不是Func。这将使你有更多的机会获得信息。