gpt4 book ai didi

c# - 将反射与标准调用混合

转载 作者:太空宇宙 更新时间:2023-11-03 21:41:34 25 4
gpt4 key购买 nike

首先让我说我对反射完全陌生。

我有一个 DictionarystringFunc<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);

一旦创建了委托(delegate),就可以毫无问题地将它放入字典中。

所以像这样:

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()相反,如果您已经知道程序集,您将在其中找到该方法。

关于c# - 将反射与标准调用混合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19058496/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com