呼叫方法的替代方法
我有一个接受两个参数字符串和对象的通用方法。它应该根据字符串名称调用一种方法。将其他参数作为对象接收,该对象基本上是目标方法的对象参数。
我目前正在维护一部词典,该字典使词典反对通过字符串和实际方法。 就像
public static Dictionary<string, string> ActionMappings = new Dictionary<string, string>
{
{ "Get Patients", "Patient.GetPatients" },
/// other mapping...
};
我目前正在根据ActionMappings词典调用该方法。我正在使用反射,就像
string className = methodDetailsValues.Split('.')[0];
string methodName = methodDetailsValues.Split('.')[1];
currMethodClass = Type.GetType("NameSpace" + className);
ConstructorInfo stringConstructor = allConstructorsOfClass.First();
object newStringConstructor = stringConstructor.Invoke(null);
MethodInfo voidMethodInfo = currMethodClass.GetMethod(methodName);
object jsonString = voidMethodInfo.Invoke(newStringConstructor, new object[] { });
我可以维护初始化方法的列表吗?它正在工作,但性能似乎很慢。
I have a generic method that accepts two parameters string and object. It is supposed to invoke a method based on string name. The other parameter is received as object which is basically object parameter of the target method.
I am currently maintaining a dictionary that keeps dictionary against passed string and the actual method.
Like
public static Dictionary<string, string> ActionMappings = new Dictionary<string, string>
{
{ "Get Patients", "Patient.GetPatients" },
/// other mapping...
};
I am currently invoking the method based on ActionMappings dictionary. I am using reflection like
string className = methodDetailsValues.Split('.')[0];
string methodName = methodDetailsValues.Split('.')[1];
currMethodClass = Type.GetType("NameSpace" + className);
ConstructorInfo stringConstructor = allConstructorsOfClass.First();
object newStringConstructor = stringConstructor.Invoke(null);
MethodInfo voidMethodInfo = currMethodClass.GetMethod(methodName);
object jsonString = voidMethodInfo.Invoke(newStringConstructor, new object[] { });
Can I maintain a list of initialized methods? It is working but it seems to be slow in performance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果所有方法都返回
字符串
且没有参数,则可以使用dictionary&lt; string,func&lt; string&gt;&gt;
这样解决此问题。类似的字典:
如果出于某种原因,您必须创建(或以某种方式获取)用于在呼叫时间返回值的对象,则可以执行类似的操作:
此方法确实要求所有方法返回相同的类型并接受相同的参数。
处理方法参数
假设该方法都接受字符串参数并返回字符串,例如,
您可以使用
func&lt; string,string&gt;
作为字典值,像这样:If all the methods return
string
and take no parameters, you can solve this by using aDictionary<string, Func<string>>
like so:Then you could use the dictionary like so:
If for some reason you must create (or somehow obtain) the objects used to return the values at call-time, you can do something like this:
This approach does require that all the methods return the same type and accept the same parameters.
Handling method parameters
Suppose that the methods all accept a string parameter and return a string, e.g. like this:
Then you could use
Func<string, string>
for the dictionary values, like so: