【问题标题】:How to invoke a MethodInfo from a Dictionary without having the original method type?如何在没有原始方法类型的情况下从字典中调用 MethodInfo?
【发布时间】:2021-04-01 08:12:41
【问题描述】:

我正在开展一个项目,该项目采用用户定义的方法并使用它们与一些数据进行交互。

现在,我有这样的事情:

(主要)

 ...
 string dllFile = @"C:\Path\GenericTester" + commandValue + ".dll";
 var assembly = Assembly.LoadFile(dllFile);

 var type = assembly.GetType("DllNamespace.DllClass");

 string methodName = "FunctionForProperty" + commandValue; //commandValue is a string of a number

 var method = type.GetMethod(methodName);

 PropertiesDictionary.updateValue(int.Parse(commandValue), method);
 ...

PropertiesDictionary 类:

static public class PropertiesDictionary
{
   public static Dictionary<int, MethodInfo> PropertiesMethods = new Dictionary<int, MethodInfo>();
                                                       
   public static void updateValue(int propertyId, MethodInfo method)
   {
      PropertiesMethods[propertyId] = method;
   }

   public static MethodInfo doFunctionForProperty(int propertyId)
   {                                         
      if (PropertiesMethods.ContainsKey(propertyId))
             return PropertiesMethods[propertyId];
      else
             return null;
   }
        
}

所以,我正在尝试做这样的事情:

 MethodInfo method = ProjectNamespace.PropertiesDictionary.doFunctionForProperty(PropertyId);
 var result = method.Invoke(null, new object[] { ParametersOfTheFunctionOfTheDll });
 return result;

当我调用最后几行时,我将无法再访问 DLL(因为我们希望将来只将编译后的代码作为 System.Reflection.Assembly Load(byte[]) 传递,并且我们只会访问该信息一次)

问题显然是我没有将对象目标传递给method.Invoke(),就像var obj = Activator.CreateInstance(type);,但我想我不知道我应该指向什么类型。

是否有更清洁的方法来实现我想要的?比如,将整个方法从System.Reflection.Assembly Load(byte[]) 中的一个类传递给 Dictionary,而不仅仅是 MethodInfo,这样我就可以在任何我想要的地方调用它,而不必传递目标?

【问题讨论】:

  • “原始方法类型”是什么意思?所有方法都具有相同的签名吗?
  • “原始方法类型”是指用户最初声明该方法的类。我想调用仅将信息存储在字典中的方法,而不必再次指向 Reflection.Assembly。不,每种方法都有不同的通用签名(如“Property”+PropertyId)。
  • 第一部分很简单:MemberInfoMethodInfo 通过MethodBase 派生而来)有一个名为DeclaringType 的属性。

标签: c# dictionary methods


【解决方案1】:

我刚刚通过将用户定义的方法设置为静态解决了这个问题,所以我不必再传递目标了。但是我认为这不是最好的解决方案,但现在它对我有用。

【讨论】:

    猜你喜欢
    • 2012-09-20
    • 1970-01-01
    • 1970-01-01
    • 2021-01-07
    • 1970-01-01
    • 2013-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多