简体   繁体   中英

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> . 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 . 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:

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM