Today I accidentally see this article LINQ beyond queries:strong-typed Reflection, found that LINQ in addition to queries can also be used in other areas, this article is mainly about how to use LINQ to achieve strong type of reflection.
Usually when using reflection, the runtime throws an exception if the method name is incorrectly written incorrectly or if the parameter type does not match. In general we write code to get MethodInfo:
MethodInfo mi = typeof(MyTest).GetMethod("TestFunc",new Type[]{ typeof (string), typeof(int)});
If you refactor the MyTest class, changing the name of the method or the type of the parameter, the runtime is sure to get an exception because these errors are not checked during compilation. If there is a lot of reflection in the project, there is no doubt that a little change can lead to potential problems. Now that LINQ is present, strong-type reflection can be achieved through the lambda expression tree. The following is the example I wrote in the test code, because now the API has some changes, the specific introduction can see the original:
public class myreflection
{
public delegate void Operation<t> (T declaringtype);
public delegate void Operation<t, A1, a2> (T declaringtype, Object A1, Object A2);
Public delegate Object Operationwithreturnvalue<t> (T declaringtype);
public static MethodInfo method<t> (Expression<operation<t>> method)
{
Return Getmethodinfo (method);
}
public static MethodInfo method<t> (expression<operationwithreturnvalue<t>> meth OD)
{
Return Getmethodinfo (method);
public static MethodInfo method<t, A1, a2> (expression<operation<t, A1, a2>> method)
{
Return Getmethodinfo (method);
}
private static MethodInfo Getmethodinfo (Expression method)
{
LambdaExpression LA MBDA = method as LambdaExpression;
if (lambda = = null)
throw new ArgumentNullException ();
Methodcallexpression methodexpr = null;
if (lambda. Body.nodetype = = expressiontype.call)
methodexpr = lambda. Body as methodcallexpression; The
Else if (lambda). Body.nodetype = = Expressiontype.convert)
methodexpr = ((unaryexpression) lambda. Body). Operand as Methodcallexpression;
if (methodexpr = = null)
throw new ArgumentException ();
return methodexpr.method;
}
}