[英]Mixing Reflection with Standard Calls
Let me preface this by saying that I am completely new to reflection. 让我先说一下,我完全不喜欢反思。
I have a Dictionary
of string
to Func<string, string>
. 我有一个
Dictionary
string
到Func<string, string>
。 I'd like to add a configuration section that would allow me to define the name of static methods that can be programmatically added into this dictionary. 我想添加一个配置部分,允许我定义可以通过编程方式添加到此字典中的静态方法的名称。
So basically, I'd have something like this: 所以基本上,我会有这样的事情:
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;
}
Is it possible to do this, or do I need everything invoked through reflection? 是否可以这样做,还是我需要通过反射调用所有东西?
I think all you're looking for is Delegate.CreateDelegate
. 我想你要找的就是
Delegate.CreateDelegate
。 You'll need to break the name you've got into a class name and a method name. 你需要打破你的名字和方法名称。 You can then use
Type.GetType()
to get the type, then Type.GetMethod()
to get the MethodInfo
, then use: 然后,您可以使用
Type.GetType()
来获取类型,然后使用Type.GetMethod()
来获取MethodInfo
,然后使用:
var func = (Func<string, string>) Delegate.CreateDelegate(
typeof(Func<string, string>), methodInfo);
Once you've created the delegate, you can put it into the dictionary with no problems. 一旦创建了委托,就可以毫无问题地将它放入字典中。
So something like: 所以类似于:
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);
}
Note that Type.GetType()
will only find types in the currently executing assembly or mscorlib
unless you actually specify an assembly-qualified name. 请注意,
Type.GetType()
只能在当前正在执行的程序集或mscorlib
查找类型,除非您实际指定了程序集限定名称。 Just something to consider. 只是需要考虑的事情。 You might want to use
Assembly.GetType()
instead if you already know the assembly you'll be finding the method in. 如果您已经知道要在其中找到方法的程序集,则可能需要使用
Assembly.GetType()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.