如何使用自动类型转换来展开对象数组以进行函数调用?

时间:2018-09-20 09:07:07

标签: c#

我正在寻找一种基于给定函数签名将参数对象数组转换为正确参数类型的方法,如以下示例所示:

buoysimoptions['SeaParameters']['phase']

c#中是否有库或某些功能提供类似方法>>> phase = buoysimoptions['SeaParameters']['phase'] >>> phase array([[array([[1.57079633]])]], dtype=object) >>> phase = buoysimoptions['SeaParameters']['phase'][0] >>> phase array([array([[1.57079633]])], dtype=object) >>> phase = buoysimoptions['SeaParameters']['phase'][0][0] >>> phase array([[1.57079633]]) 的内容?

2 个答案:

答案 0 :(得分:1)

您可以使用反射来实现。价格是性能,没有编译时间检查。

 typeof(MyType).GetMethod("add").Invoke(null, new [] {arg1, arg2})

示例取自:how to dynamically call a function in c#

要决定要使用哪个功能,我将使用反射GetParameters()(请参阅https://docs.microsoft.com/en-us/dotnet/api/system.reflection.methodbase.getparameters)检查可用的功能,并将结果缓存到字典中。

正如其他人已经提到的:尽管在特殊情况下这可能是一种有效的方法-在大多数情况下,这不是您应该在C#中执行的方法。

答案 1 :(得分:0)

到目前为止,我最终做了类似的事情

private void Apply(string functionName, object[] args) {
  var methodInfo = typeof(Class).GetMethod(functionName, BindingFlags.Instance,
                    Type.DefaultBinder, args.Select(_ => _.GetType()).ToArray(), null);
  if (methodInfo == null) {
    // error handling - throw appropriate exception
  } else {
    methodInfo.Invoke(this, args);
  }
}

这需要将Apply(CaseA,args)的原始呼叫更改为Apply(nameof(CaseA),args)

仍然欢迎任何更优雅的解决方案。

相关问题