我有以下课程(使用私人.ctor和公共工厂方法)
public class TypeWithFactoryMethods
{
private TypeWithFactoryMethods()
{
}
public static TypeWithFactoryMethods Create()
{
return new TypeWithFactoryMethods();
}
}
通过反射调用公共工厂方法(Create)的最佳方法是什么,这样我就可以获得该类型的实例?
答案 0 :(得分:3)
不太确定目标是什么,但这样做会:
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
}
答案 1 :(得分:0)
相同结果的代码较少:
var param = Expression.Parameter(typeof (TypeWithFactoryMethods));
var method = Expression.Call(null,typeof(TypeWithFactoryMethods).GetMethod("Create"));
Expression.Lambda<Action>(method).Compile()();