Converting Object to type Dynamic in C#

雨燕双飞 提交于 2020-02-20 07:07:05

问题


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.

Code 1:

object objSum;
dynamic dynSum;
objSum = dataTableColumnChart.Compute(String.Format("Count({0})", strColumnName), "");
dynSum = Convert.ChangeType(objSum, objSum.GetType());\
Debug.Writeline(dynSum);

Code 2:

dynSum=objSum;
Debug.Writeline(dynSum);

The exception thrown is this:

A first chance exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in Unknown Module.

Please note that in both cases exception is thrown when Debug statement is executed.


回答1:


The exception is:

Cannot dynamically invoke method 'Write' because it has a Conditional attribute

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);

Hope this helps

*Edit: 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's type is dynamic { string }




回答2:


Here is extension method to convert an object to Dynamic

public static dynamic ToDynamic(this object value)
    {
        IDictionary<string, object> expando = new ExpandoObject();

        foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(value.GetType()))
            expando.Add(property.Name, property.GetValue(value));

        return expando as ExpandoObject;
    }



回答3:


you should use JsonConvert. Fist of all, Serialize object to string, then Deserialize string to dynamic.

string str = JsonConvert.SerializeObject(objectstring);
dynamic obj = JsonConvert.DeserializeObject(str);



回答4:


Try the following:

dynSum = objSum;


来源:https://stackoverflow.com/questions/36147932/converting-object-to-type-dynamic-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!