为什么在调用方法时使用json.net与动态获取RuntimeBinderException [英] Why do I get a RuntimeBinderException using json.net with dynamic when calling a method
问题描述
为什么当我使用json.net动态时,我得到一个运行时绑定异常,然后调用一个方法而不进行转换,但是我可以做任务没有问题
Why is it that when I use dynamic with json.net I get a runtime binding exception then calling a method without casting but I can do assignments not problem
private static void Main()
{
dynamic json = JObject.Parse("{\"Test\":23}");
var t = json.Test;
int a = t; //Success
Prop = t; //Success
Func(t); //RuntimeBinderException
}
private static void Func(int i){}
private static int Prop { get; set; }
当我将其转换为正确的类型时,没有错误,但我宁愿不必去做。我做错了,这是json.net库中的一个问题,还是一个语言限制。
When I cast it to the correct type there are no errors but I would prefer to not have to do that. Am I doing something wrong, is this a problem in the json.net library or is a language restriction.
编辑:
这是为了解决一个问题,我不能控制方法签名,我不想在每次调用时都转换它。
This is to solve a problem where I don't have control over the methods signature and I don't want to cast it on every call.
推荐答案
这是因为 json.Test
返回一个 JValue
和 JValue
有一个动态 TryConvert
。因此,如果您通过将其指向 int
或转换为 int
来进行隐式静态转换,则它将在运行时调用那个 TryConvert
,你有成功。但是,如果在方法参数中使用动态类型的变量,c#运行时将查找一个名为 Func
的方法,其中一个参数与JValue最匹配,它不会尝试调用'TryConvert'用于可能方法的每个排列(即使只有一个),因此您得到运行时绑定错误。
This is because json.Test
returns a JValue
and JValue
has a dynamic TryConvert
. So if you do an implicit static conversion by pointing it to an int
or cast to an int
it will at runtime call that TryConvert
and you have success. However if you use that dynamically typed variable in a method argument, the c# runtime looks for a method named Func
with an argument that best matches 'JValue' it will not try to call 'TryConvert' for every permutation of a possible method (even if it's only one) thus you get the runtime binding error.
所以最简单的解决方案是每个调用或设置一个静态类型的变量,每次要传递一个 JValue
作为参数。
So the simplest solution is to just cast on every call or set a statically typed variable each time you want to pass a JValue
as an argument.
如果您正在寻找更多的信息,那么这个同样问题的一般问题和答案也是如此:
在C#4中的方法的静态参数中传递动态变量
There is actually a more general question and answer of this same issue too if you are looking for more info: Pass a dynamic variable in a static parameter of a method in C# 4
这篇关于为什么在调用方法时使用json.net与动态获取RuntimeBinderException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!