我有以下类(私有. tor和公共工厂方法)
public class TypeWithFactoryMethods
{
private TypeWithFactoryMethods()
{
}
public static TypeWithFactoryMethods Create()
{
return new TypeWithFactoryMethods();
}
}
通过反射调用公共工厂方法(Create)的最佳方法是什么,以便我可以获得该类型的实例?
不太确定目标是什么,但是可以这样做:
Type type = typeof(TypeWithFactoryMethods);
MethodInfo info = type.GetMethod("Create", BindingFlags.Static | BindingFlags.Public);
object myObject = info.Invoke(null, null);
myObject.GetType(); //returns TypeWithFactoryMethods
注释后更新
如果你想找到所有返回你指定类型的方法,你可以使用Linq来找到它们:
Type type = typeof(TypeWithFactoryMethods);
List<MethodInfo> methods = type.GetMethods(BindingFlags.Static | BindingFlags.Public)
.Where(m => m.ReturnType == type).ToList();
foreach (var method in methods)
{
ParameterInfo[] parameters = method.GetParameters(); //use parameters to decide how to invoke
object myObject = method.Invoke(null, null);
myObject.GetType(); //returns TypeWithFactoryMethods
}
相同结果的代码更少:
var param = Expression.Parameter(typeof (TypeWithFactoryMethods));
var method = Expression.Call(null,typeof(TypeWithFactoryMethods).GetMethod("Create"));
Expression.Lambda<Action>(method).Compile()();