C#: Dynamic runtime cast

前端 未结 9 2233
情深已故
情深已故 2020-11-27 03:50

I would like to implement a method with the following signature

dynamic Cast(object obj, Type castTo);

Anyone know how to do that? obj defi

9条回答
  •  旧时难觅i
    2020-11-27 04:00

    Slight modification on @JRodd version to support objects coming from Json (JObject)

    public static dynamic ToDynamic(this object value)
        {
            IDictionary expando = new ExpandoObject();
    
            //Get the type of object 
            Type t = value.GetType();
    
            //If is Dynamic Expando object
            if (t.Equals(typeof(ExpandoObject)))
            {
                foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(value.GetType()))
                    expando.Add(property.Name, property.GetValue(value));
            }
            //If coming from Json object
            else if (t.Equals(typeof(JObject)))
            {
                foreach (JProperty property in (JToken)value)
                    expando.Add(property.Name, property.Value);
            }
            else //Try converting a regular object
            {
                string str = JsonConvert.SerializeObject(value);
                ExpandoObject obj = JsonConvert.DeserializeObject(str);
    
                return obj;
            }
    
           
    
            return expando as ExpandoObject;
        }
    

提交回复
热议问题