簡體   English   中英

將反射與標准調用混合

[英]Mixing Reflection with Standard Calls

讓我先說一下,我完全不喜歡反思。

我有一個Dictionary stringFunc<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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM