如何检测ExpandoObject与动态对象?

时间:2018-07-01 02:47:57

标签: c# object

如何确定Type是ExpandoObject还是Dynamic对象?

这两个都返回true:

public static bool IsDynamicObject(Type type)
{
    return typeof(IDynamicMetaObjectProvider).IsAssignableFrom(type);
}

动态对象的示例代码:

public class Entity
{
    public Guid Id { get; set; }
    public String Name { get; set; }
}

Delta<Entity> x = new Delta<Entity>();
dynamic dynamicX = x;
dynamicX.Name = nameof(Entity);
dynamicX.Id = typeof(Entity).GUID;

Expando对象的示例代码:

dynamic childX = new ExpandoObject();
childX.A = 1;

1 个答案:

答案 0 :(得分:0)

ExpandoObject可以转换为字典以获取成员名称和值

public static bool IsExpandoObject(object objectValue)
{
    if (objectValue == null)
        return false;

    if (IsDynamicObject(objectValue.GetType()))
    {
        IDictionary<string, object> expandoPropertyValues = objectValue as IDictionary<string, object>;
        return expandoPropertyValues != null;
    }

    return false;
}

public static bool IsDynamicObject(Type type)
{
    return typeof(IDynamicMetaObjectProvider).IsAssignableFrom(type);
}