为什么我调用方法时,使用json.net动态获得RuntimeBinderException [英] Why do I get a RuntimeBinderException using json.net with dynamic when calling a method

查看:131
本文介绍了为什么我调用方法时,使用json.net动态获得RuntimeBinderException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么当我使用动态与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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆