我正在尝试将对象转换为动态类型,但由于RunTimeBinder异常而转换失败 [英] I am trying to convert an Object to dynamic type but the conversion is failing with RunTimeBinder exception
问题描述
我正在尝试将Object转换为动态类型,但是由于RunTimeBinder异常而转换失败.我尝试使用在Stackoverflow答案中遇到的两种方法.
I am trying to convert an Object to dynamic type but the conversion is failing with RunTimeBinder exception. I tried using two methods that I came across in Stackoverflow answers.
代码1:
object objSum;
dynamic dynSum;
objSum = dataTableColumnChart.Compute(String.Format("Count({0})", strColumnName), "");
dynSum = Convert.ChangeType(objSum, objSum.GetType());\
Debug.Writeline(dynSum);
代码2:
dynSum=objSum;
Debug.Writeline(dynSum);
抛出的异常是这样:
A first chance exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in Unknown Module.
请注意,在两种情况下,执行Debug语句均会引发异常.
Please note that in both cases exception is thrown when Debug statement is executed.
推荐答案
例外是:
Cannot dynamically invoke method 'Write' because it has a Conditional attribute
当您检查可能的Debug.WriteLine输入时,动态"不是其中之一. 因此,您需要将其强制转换为字符串:
And when you check possible Debug.WriteLine inputs, "dynamic" is not one of them. So you need to cast it, to string for example:
string strForWriteLine = dynSum.ToString() as string;
Debug.WriteLine(strForWriteLine);
希望这会有所帮助
* 关于 dynSum.ToString()作为字符串的一些细节; 当您只使用ToString()时,您仍然会得到一个动态字符串.
* A little bit detail about dynSum.ToString() as string; When you just use ToString() you still get a dynamic string.
var strForWriteLine = dynSum.ToString();
strForWriteLine的类型为 dynamic {字符串}
strForWriteLine's type is dynamic { string }
这篇关于我正在尝试将对象转换为动态类型,但由于RunTimeBinder异常而转换失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!