c# - 没有参数的方法如何分配给 ExpandoObject?

标签 c# dynamic-language-runtime expandoobject

我正在尝试将方法(函数)分配给具有此签名的 ExpandoObject:

public List<string> CreateList(string input1, out bool processingStatus)
{
  //method code...
}

我试过做一些像下面这样的代码,但它无法编译:

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;
                });

不幸的是,我无法更改 CreateList 签名,因为它会破坏向后兼容性,因此重写它不是一种选择。我试图通过使用委托(delegate)来解决这个问题,但在运行时,我得到了一个“无法调用非委托(delegate)类型”的异常。我想这意味着我没有正确分配委托(delegate)。我需要帮助使语法正确(委托(delegate)示例也可以)。谢谢!!

最佳答案

此示例按预期编译和运行:

dynamic obj = new ExpandoObject();
obj.Method = new Func<int, string>((i) =>
    {
        Console.WriteLine(i);
        return "Hello World";
    });

obj.Method(10);
Console.ReadKey();

你的陈述的问题在于你的 Func 不像你的签名那样使用输出参数。

(input1, out processingStatus)

如果你想分配你当前的方法,你将无法使用 Func,但你可以创建你自己的委托(delegate):

    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 };
    }

关于c# - 没有参数的方法如何分配给 ExpandoObject?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5425762/

相关文章:

c# - 如何将 PostSharp 与最小起订量一起使用?

c# - 实例化委托(delegate) (Func<T, T>) 的各种方式之间的区别?

c# - 在 IronRuby 中包含接口(interface)的问题

c# - 如何将 gridview 数据绑定(bind)到 ExpandoObject

c# - 我怎样才能保护字符串,例如C#

c# - FileNameSizeDelimiteC 必须是常量

ternary-operator - 如何在DLR中实现三元运算符

c# - 是否可以使用 DLR 加载和执行 C# 代码片段?

c# - 使用 Expando 对象时如何将类型设置为可为空

c# - 如何使用 ServiceStack JsonSerializer 序列化 ExpandoObject?