现在有这样一个基本类
using System;
namespace ReflectClassAndMethod
{
public class AController
{
public int MyProperty { get; set; }
public String Get(String str)
{
return "AController Get " + str;
}
public string Set(string str) => "AController Set " + str;
}
}
分别用反射和表达式树来实现调用其方法
using System;
using System.Linq.Expressions;
using System.Reflection;
namespace ReflectClassAndMethod
{
class Program
{
static void Main(string[] args)
{
while (true)
{
String str = Console.ReadLine();
if (str == "x") break;
Console.WriteLine(Execute(str));
}
}
static String Execute(String str)
{
string[] strArray = str.Split('/');
ExcuteDetail detail = new ExcuteDetail()
{
Controller = strArray[0],
Method = strArray[1],
Argument = strArray[2]
};
//return detail.ExecuteByReflection();
return detail.ExecuteByExpression();
}
}
public class ExcuteDetail
{
public String Controller { get; set; }
public String Method { get; set; }
public String Argument { get; set; }
/// <summary>
/// 反射调用
/// </summary>
/// <returns></returns>
public String ExecuteByReflection()
{
//命名空间
string @namespace = MethodBase.GetCurrentMethod().DeclaringType.Namespace;
//获取类型
Type type = Type.GetType($"{@namespace}.{Controller}Controller");
if (type != null)
{
//构造函数获取对象
ConstructorInfo constructorInfo = type.GetConstructor(new Type[] { });
object o = constructorInfo.Invoke(new object[] { });
AController aController = o as AController;
//AController aController = (AController)Activator.CreateInstance(type);
MethodInfo methodInfo = type.GetMethod(Method);
string result = methodInfo.Invoke(aController, new object[] { Argument }).ToString();
return result;
}
return "";
}
/// <summary>
/// 表达式树
/// </summary>
/// <returns></returns>
public String ExecuteByExpression()
{
//命名空间
string @namespace = MethodBase.GetCurrentMethod().DeclaringType.Namespace;
//获取类型
Type type = Type.GetType($"{@namespace}.{Controller}Controller");
MethodInfo methodInfo = type.GetMethod(Method);
AController aController = (AController)Activator.CreateInstance(type);
ParameterExpression paramo = Expression.Parameter(type, Controller);
ParameterExpression parami = Expression.Parameter(typeof(string), "str");
MethodCallExpression methodCall = Expression.Call(paramo, methodInfo, parami);
Console.WriteLine(methodCall.ToString());
Expression expressionLambda = Expression.Lambda(methodCall, paramo, parami);
Expression<Func<AController, string, string>> lambda = (Expression<Func<AController, string, string>>)expressionLambda;
Func<AController, string, string> func = lambda.Compile();
return func?.Invoke(aController, Argument);
}
}
}
测试输入:A/Get/hello world
输出