【发布时间】: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)。
-
第一部分很简单:
MemberInfo(MethodInfo通过MethodBase派生而来)有一个名为DeclaringType的属性。
标签: c# dictionary methods