dquv73115 2014-01-15 16:17
浏览 25
已采纳

如何在C#中表示Golang的界面{}?

I'm trying to convert some Go code to C#. In Go there is, in example:

type MyType interface{}

Is this something like object in C# or MyType<T>?

In Go code, there is an array of these interfaces and every one of them returns a function with different arguments.

I can return List of Funcs in C# but then the dynamic arguments are the problem.

I'm having problems about representing this in C#. Need some guidance to find the right path.

  • 写回答

1条回答 默认 最新

  • douzhuiqing1151 2014-01-15 16:46
    关注

    By far the best option is to just avoid this entirely. Rather than accepting both a delegate and a list of arguments that should be passed to it when invoked, just require all of the delegates to be parameterless (i.e. Action). It is then the responsibility of the caller, if they wish to have a method run with a given set of arguments, to wrap it in a parameterless method that invokes the given function with a fixed set of arguments. This can be done conveniently using a lambda in most circumstances, so this is not a burdonsome request for the caller; in fact, it's generally going to be easier on them then specifying a function and an argument list.

    Your method signature then becomes:

    public void Foo(Action action) {}
    

    And to the caller it'll be:

    Foo(() => SomeMethod(firstArgument, secondArgument));
    

    You can then make a List<Action> from those actions which you can easily invoke without messing around with reflection or dynamic typing. This solution maintains entirely compile time checking of all functions and their arguments, so you don't need to worry about dealing with invalid arguments being supplied.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入