Invoking Member of a class using Class Name and Method Name

前端 未结 2 731
粉色の甜心
粉色の甜心 2021-01-07 05:04

I am trying to invoke function of a class using Reflection (assuming that object initialization as no dependency on Function to be invoked) like this



        
相关标签:
2条回答
  • 2021-01-07 05:25

    To answer you query on dynamic; no, that wouldn't be a good fit here. dynamic is useful when the member-name (or operation) is known at compile-time, but is not provable to exist - basically, duck-typing. For example:

    dynamic foo = GetSomeRandomObject();
    foo.ThisShouldExist("abc");
    

    this does similar things, but the usage is different. So yes, you're left with reflection. What you are doing is pretty-much right. The only thing I might change would be to obtain the MethodInfo, and work from there - although if you can change the API to accept a single string assemblyQualifiedName it would be more convenient and flexible. But perhaps:

    public static string InvokeStringMethod5(string assemblyName,
        string namespaceName, string typeName, string methodName, string stringParam)
    {
        string assemblyQualifiedName = string.Format("{0}.{1},{2}",
            namespaceName, typeName, assemblyName);
        Type calledType = Type.GetType(assemblyQualifiedName);
        if(calledType == null) throw new InvalidOperationException(
            assemblyQualifiedName + " not found");
        MethodInfo method = calledType.GetMethod(methodName,
            BindingFlags.Public | BindingFlags.Static);
        switch (method.GetParameters().Length)
        {
            case 0:
                return (string)method.Invoke(null, null);
            case 1:
                return (string)method.Invoke(null, new object[] { stringParam });
            default:
                throw new NotSupportedException(methodName
                    + " must have 0 or 1 parameter only");
        }
    }
    
    0 讨论(0)
  • 2021-01-07 05:38

    To answer the question on how to cast the result to a generic return type, the method would look something like:

    public static T InvokeMethod<T>(string assemblyName, string namespaceName, string typeName, string methodName, string stringParam)
    {
        // instead of String s = null;
        T methodResult = default(T);
    
        // instead of s = (String)calledType.InvokeMember(...)
        methodResult = (T)calledType.InvokeMember(...);
    
        // return s;
        return methodResult;
    }
    
    0 讨论(0)
提交回复
热议问题