Six*_*aez 1 c# dynamic-language-runtime expandoobject
我正在尝试使用此签名为ExpandoObject分配方法(函数):
public List<string> CreateList(string input1, out bool processingStatus)
{
//method code...
}
Run Code Online (Sandbox Code Playgroud)
我尝试过这样的代码,下面的代码不能编译:
dynamic runtimeListMaker = new ExpandoObject();
runtimeListMaker.CreateList =
new Func<string, bool, List<string>>(
(input1, out processingStatus) =>
{
var newList = new List<string>();
//processing code...
processingStatus = true;
return newList;
});
Run Code Online (Sandbox Code Playgroud)
不幸的是我无法更改CreateList签名,因为它会破坏向后兼容性,因此重写它不是一个选项.我试图通过使用委托解决这个问题,但在运行时,我得到了"无法调用非委托类型"异常.我想这意味着我没有正确分配代表.我需要帮助使语法正确(委托示例也可以).谢谢!!
此示例按预期编译并运行:
dynamic obj = new ExpandoObject();
obj.Method = new Func<int, string>((i) =>
{
Console.WriteLine(i);
return "Hello World";
});
obj.Method(10);
Console.ReadKey();
Run Code Online (Sandbox Code Playgroud)
您的语句的问题是您的Func不使用像您的签名那样的输出参数.
(input1, out processingStatus)
Run Code Online (Sandbox Code Playgroud)
如果要分配当前方法,则无法使用Func,但可以创建自己的委托:
public delegate List<int> MyFunc(int input1, out bool processing);
protected static void Main(string[] args)
{
dynamic obj = new ExpandoObject();
obj.Method = new MyFunc(Sample);
bool val = true;
obj.Method(10, out val);
Console.WriteLine(val);
Console.ReadKey();
}
protected static List<int> Sample(int sample, out bool b)
{
b = false;
return new List<int> { 1, 2 };
}
Run Code Online (Sandbox Code Playgroud)