[英]Dynamically invoke method in c#
I want to be able to store function reference and disregard arguments until it actually is used. 我希望能够存储函数引用并忽略参数,直到实际使用它为止。
Here's what I'd like for it to look like: 这是我想要的样子:
StoreType f=MyFunction;
.......
var r=f.Invoke(arg1,arg2,arg3) as ReturnType;
This is kind of like Action and Func, but those are strongly typed, and I want to be able to declare and use this type without precisely knowing how many arguments and of what types the function will take. 这有点像Action和Func,但是它们是强类型的,并且我希望能够在不精确知道函数将要使用多少个参数和类型的情况下声明和使用此类型。
How do I do this in c#? 我该如何在C#中执行此操作?
For the argument count, just pass an array of object containing the arguments. 对于参数计数,只需传递包含参数的对象数组。
f.Invoke(new object[]{ arg1, args2, args3, ... });
For the type use the method 对于类型使用方法
Convert.ChangeType(objectToConvert, destinationType);
Should work for me :) 应该为我工作:)
您可以使用较旧的delegate
语法。
public delegate ReturnType MyFunction(string arg1, int arg2, ...);
var result = MyFunction.Invoke(arg1, arg2, ...);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.