使用反射将动态对象转换为类型(C#)

16

请考虑以下代码

 var currentType = Type.GetType("Some.Type, Some");
 dynamic myDynamic = new System.Dynamic.ExpandoObject();
 myDynamic.A = "A";
 var objectInCorrectType = ???

我该如何将动态类型转换为当前类型?


6
你不能直接将 ExpandoObject 类型转换为其他特定类型,需要通过重新解释类型或者进行手动的代码转换来实现。重新解释类型使用 reinterpretation cast,它会告诉编译器“我知道这个引用实际上是 X 而不是 Y,所以请将其转换为 X 类型”。而进行手动代码转换时,则需要编写代码来创建一个新的 X 对象并复制值等步骤。没有内置的方法可以从 ExpandoObject 类型转换或转换为其他特定类型,需要自己构建转换代码。 - Lasse V. Karlsen
3个回答

14

正如 @Lasse 评论所述,您不能将动态对象强制转换为特定类型。

但是,由于您的问题涉及“反射”,因此我怀疑您正在寻找一种简单映射属性值的方法(例如在 Lasse 的评论中提到的“创建新 X 并复制值等”):

...
myDynamic.A = "A";

// get settable public properties of the type
var props = currentType.GetProperties(BindingFlags.Public | BindingFlags.Instance)
    .Where(x => x.GetSetMethod() != null);

// create an instance of the type
var obj = Activator.CreateInstance(currentType);

// set property values using reflection
var values = (IDictionary<string,object>)myDynamic;
foreach(var prop in props)
    prop.SetValue(obj, values[prop.Name]);

我会排除 properties.Where(p => p.GetIndexParameters().Length > 0),否则您也会包括索引器。我还相信 GetSetMethod 并不保证 public,即使您请求了 BindingFlags.Public,因为属性是 getter 和 setter 方法的代理,它们可能具有不同的访问修饰符。 - user11523568

9

dynamic鸭子类型 的变量(即将类型检查延迟到运行时)。它仍然持有一个类型化对象,但在编译时不进行检查。

因此,由于 ExpandoObject 是一种类型,无论您将其分配给类型化或动态引用,您都不能将 ExpandoObject 强制转换或转换为类型,只是因为它与目标类型共享相同的成员。

顺便说一下,由于 ExpandoObject 实现了 IDictionary<string,object>,您可以通过扩展方法实现从 ExpandoObject 实例到目标类型的即时映射,其中成员作为匹配项:

public static class ExpandObjectExtensions
{
    public static TObject ToObject<TObject>(this IDictionary<string, object> someSource, BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public)
           where TObject : class, new ()
    {
        Contract.Requires(someSource != null);
        TObject targetObject = new TObject();
        Type targetObjectType = typeof (TObject);

        // Go through all bound target object type properties...
        foreach (PropertyInfo property in 
                    targetObjectType.GetProperties(bindingFlags))
        {
            // ...and check that both the target type property name and its type matches
            // its counterpart in the ExpandoObject
            if (someSource.ContainsKey(property.Name) 
                && property.PropertyType == someSource[property.Name].GetType())
            {
                property.SetValue(targetObject, someSource[property.Name]);
            }
        }

        return targetObject;
    }
}

现在,尝试以下代码,它将按照您的预期工作:

public class A 
{
    public int Val1 { get; set; }
}

// Somewhere in your app...
dynamic expando = new ExpandoObject();
expando.Val1 = 11;

// Now you got a new instance of A where its Val1 has been set to 11!
A instanceOfA = ((ExpandoObject)expando).ToObject<A>();

实际上,我基于其他问答的答案来回答这个问题,那里我可以解决类似将对象映射到字典和反之的问题:将对象映射到字典和反之.


这正是我要找的,谢谢。 - John Willemse

0

我遇到了这个问题,因为我需要上这样的课程:

public class PropertyChange
{
    [JsonProperty("name")]
    public string PropertyName { get; set; }

    [JsonProperty("value")]
    public string PropertyValue { get; set; }

    [JsonProperty("arrayValue")]
    public dynamic[] PropertyArray { get; set; }
}

将对象的 PropertyArray 属性(使用Newtonsoft库从JSON反序列化)转换为特定类型的对象数组,其中类型可以由 PropertyName 推导出来。

我写了这个名为 DynamicCast <> 的助手类,并决定在这里发布,以防其他人与我处于相同的情况。

此助手类允许您编写以下代码:

public class MyType
{
    public string A { get; set; }
}

var myCast = new DynamicCast<MyType>();

dynamic dyn = ExpandoObject();
dyn.A = "Hello";

var myType = myCast.Cast(dyn);
Console.WriteLine(myType.A); // prints 'Hello'

这是我如何使用它来解决我的反序列化问题的示例:

public class JsonTest
{
    [JsonProperty("theArray")]
    public dynamic[] TheArray { get; set; }
}

var json = "{'theArray':[{'a':'First'},{'a':'Second'}]}";
var jsonTest = JsonConvert.DeserializeObject<JsonTest>(json);

var myCast = new DynamicCast<MyType>();
var myTypes = myCast.Cast(jsonTest.TheArray).ToArray();
Console.WriteLine(myTypes[0].A); // prints 'First'

根据其他答案,他编写了DynamicCast类。代码如下:

public class DynamicCast<T> where T: class, new()
{
    private Property[] _proprties;

    public DynamicCast()
    {
        _proprties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance)
            .Where(x => x.GetSetMethod() != null)
            .Where(x => x.GetGetMethod() != null)
            .Select(p =>
            {
                var property = new Property
                {
                    PropertyInfo = p,
                    Name = p.Name
                };
                foreach (var attribute in p.GetCustomAttributes(false))
                {
                    if (attribute.GetType() == typeof(JsonPropertyAttribute))
                    {
                        var jsonProperty = (JsonPropertyAttribute)attribute;
                        property.Name = jsonProperty.PropertyName;
                        break;
                    }
                    if (attribute.GetType() == typeof(JsonIgnoreAttribute))
                    {
                        return null;
                    }
                }
                return property;
            })
            .Where(p => p != null)
            .ToArray();
    }

    public T Cast(IDictionary<string, object> d)
    {
        var t = new T();
        Fill(d, t);
        return t;
    }

    public T Cast(JObject d)
    {
        var t = new T();
        Fill(d, t);
        return t;
    }

    public dynamic Cast(T t)
    {
        dynamic d = new ExpandoObject();
        Fill(t, d);
        return d;
    }

    public IEnumerable<T> Cast(IEnumerable<JObject> da)
    {
        return da.Select(e => Cast(e));
    }

    public IEnumerable<T> Cast(IEnumerable<object> da)
    {
        return da.Select(e =>
        {
            if (e is JObject) return Cast((JObject)e);
            if (e is IDictionary<string, object>) return Cast((IDictionary<string, object>)e);
            return null;
        });
    }

    public void Fill(IDictionary<string, object> values, T target)
    {
        foreach (var property in _proprties)
            if (values.TryGetValue(property.Name, out var value))
                property.PropertyInfo.SetValue(target, value, null);
    }

    public void Fill(JObject values, T target)
    {
        foreach (var property in _proprties)
        {
            if (values.TryGetValue(property.Name, out var value))
            {
                if (value is JValue jvalue)
                {
                    var propertyValue = Convert.ChangeType(jvalue.Value, property.PropertyInfo.PropertyType);
                    property.PropertyInfo.SetValue(target, propertyValue, null);
                }
            }
        }
    }

    public void Fill(T obj, IDictionary<string, object> target)
    {
        foreach (var property in _proprties)
            target[property.Name] = property.PropertyInfo.GetValue(obj, null);
    }

    private class Property
    {
        public PropertyInfo PropertyInfo;
        public string Name;
    }
}

你可以在 .Net Fiddle 上自己尝试一下,链接在这里:https://dotnetfiddle.net/J1JXgU


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接