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 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误