.net 如何将对象强制转换为Func并调用?
我有一个通用方法GetValueProvider,它返回。。。代表在另一个方法中,我需要调用GetValueProvider,调用返回的委托,最后获取其返回值。但我不能直接调用它,因为我只获取类型作为参数。对于反射,获取GetValueProvider的输出不是问题,但我得到的只是对象。如何调用底层委托 这是我的代码的简化示例。最后,我需要填充值 例外情况:.net 如何将对象强制转换为Func并调用?,.net,vb.net,reflection,delegates,.net,Vb.net,Reflection,Delegates,我有一个通用方法GetValueProvider,它返回。。。代表在另一个方法中,我需要调用GetValueProvider,调用返回的委托,最后获取其返回值。但我不能直接调用它,因为我只获取类型作为参数。对于反射,获取GetValueProvider的输出不是问题,但我得到的只是对象。如何调用底层委托 这是我的代码的简化示例。最后,我需要填充值 例外情况: System.ArgumentException: Object of type 'VB$AnonymousDelegate_2`1[Sy
System.ArgumentException: Object of type 'VB$AnonymousDelegate_2`1[System.Collections.Generic.Dictionary`2[System.String,System.String]]' cannot be converted to type 'System.Func`1[System.Collections.Generic.Dictionary`2[System.String,System.String]]'.
at System.RuntimeType.TryChangeType(Object value, Binder binder, CultureInfo culture, Boolean needsSpecialCast)
at System.RuntimeType.CheckValue(Object value, Binder binder, CultureInfo culture, BindingFlags invokeAttr)
at System.Reflection.MethodBase.CheckArguments(Object[] parameters, Binder binder, BindingFlags invokeAttr, CultureInfo culture, Signature sig)
at System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Delegate.DynamicInvokeImpl(Object[] args)
at System.Delegate.DynamicInvoke(Object[] args)
...
有什么想法吗?谢谢。哦,我真蠢。实际上,代码中使用的两种方法都有效。若有人想知道,异常是由tokensProvider中的错误类型引起的。上面的示例应该可以很好地工作,我的代码中实际包含以下内容:
Dim tokensProvider As = Function() As Dictionary(Of String, String)
' some code here
End Function
修正:
Dim tokensProvider As = Function() As Dictionary(Of String, String)
' some code here
End Function
Dim tokensProvider As Func(Of Dictionary(Of String, String)) = Function() As Dictionary(Of String, String)
' some code here
End Function