[英]How can I represent Golang's interface{} in C#?
I'm trying to convert some Go code to C#.我正在尝试将一些 Go 代码转换为 C#。 In Go there is, in example:
在 Go 中有,例如:
type MyType interface{}
Is this something like object
in C# or MyType<T>
?这类似于 C# 或
MyType<T>
中的object
吗?
In Go code, there is an array of these interfaces and every one of them returns a function with different arguments.在 Go 代码中,有一个由这些接口组成的数组,每个接口都返回一个具有不同参数的函数。
I can return List of Funcs
in C# but then the dynamic arguments are the problem.我可以在 C# 中返回
List of Funcs
但动态参数就是问题所在。
I'm having problems about representing this in C#.我在用 C# 表示这个时遇到了问题。 Need some guidance to find the right path.
需要一些指导才能找到正确的路径。
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 (ie
Action
).与其同时接受委托和调用时应传递给它的参数列表,不如只要求所有委托都是无参数的(即
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;
在大多数情况下,这可以使用 lambda 方便地完成,因此这对调用者来说不是一个繁琐的请求; 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.然后,您可以从那些您可以轻松调用的操作中创建一个
List<Action>
,而不会弄乱反射或动态类型。 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.此解决方案维护所有函数及其参数的完整编译时检查,因此您无需担心处理提供的无效参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.