[英]Mixing Reflection with Standard Calls
让我先说一下,我完全不喜欢反思。
我有一个Dictionary
string
到Func<string, string>
。 我想添加一个配置部分,允许我定义可以通过编程方式添加到此字典中的静态方法的名称。
所以基本上,我会有这样的事情:
public static void DoSomething()
{
string MethodName = "Namespace.Class.StaticMethodName";
// Somehow convert MethodName into a Func<string, string> object that can be
// passed into the line below
MyDictionary["blah"] = MethodNameConvertedToAFuncObject;
MyDictionary["foo"] = ANonReflectiveMethod;
foreach(KeyValuePair<string, Func<string, string>> item in MyDictionary)
{
// Calling method, regardless if it was added via reflection, or not
Console.WriteLine(item.Value(blah));
}
}
public static string ANonReflectiveMethod(string AString)
{
return AString;
}
是否可以这样做,还是我需要通过反射调用所有东西?
我想你要找的就是Delegate.CreateDelegate
。 你需要打破你的名字和方法名称。 然后,您可以使用Type.GetType()
来获取类型,然后使用Type.GetMethod()
来获取MethodInfo
,然后使用:
var func = (Func<string, string>) Delegate.CreateDelegate(
typeof(Func<string, string>), methodInfo);
一旦创建了委托,就可以毫无问题地将它放入字典中。
所以类似于:
static Func<string, string> CreateFunction(string typeAndMethod)
{
// TODO: *Lots* of validation
int lastDot = typeAndMethod.LastIndexOf('.');
string typeName = typeAndMethod.Substring(0, lastDot);
string methodName = typeAndMethod.Substring(lastDot + 1);
Type type = Type.GetType(typeName);
MethodInfo method = type.GetMethod(methodName, new[] { typeof(string) });
return (Func<string, string>) Delegate.CreateDelegate(
typeof(Func<string, string>), method);
}
请注意, Type.GetType()
只能在当前正在执行的程序集或mscorlib
查找类型,除非您实际指定了程序集限定名称。 只是需要考虑的事情。 如果您已经知道要在其中找到方法的程序集,则可能需要使用Assembly.GetType()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.