How do I check if a property exists on a dynamic anonymous type in c#?

前端 未结 11 678
时光取名叫无心
时光取名叫无心 2020-12-01 00:20

I have an anonymous type object that I receive as a dynamic from a method I would like to check in a property exists on that object.

....
var settings = new          


        
11条回答
  •  再見小時候
    2020-12-01 01:11

    To extend the answer from @Kuroro, if you need to test if the property is empty, below should work.

    public static bool PropertyExistsAndIsNotNull(dynamic obj, string name)
    {
        if (obj == null) return false;
        if (obj is ExpandoObject)
        {
            if (((IDictionary)obj).ContainsKey(name))
                return ((IDictionary)obj)[name] != null;
            return false;
        }
        if (obj is IDictionary dict1)
        {
            if (dict1.ContainsKey(name))
                return dict1[name] != null;
            return false;
        }
        if (obj is IDictionary dict2)
        {
            if (dict2.ContainsKey(name))
                return (dict2[name].Type != JTokenType.Null && dict2[name].Type != JTokenType.Undefined);
            return false;
        }
        if (obj.GetType().GetProperty(name) != null)
            return obj.GetType().GetProperty(name).GetValue(obj) != null;
        return false;
    }
    

提交回复
热议问题