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

前端 未结 11 679
时光取名叫无心
时光取名叫无心 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:02

    In case someone need to handle a dynamic object come from Json, I has modified Seth Reno answer to handle dynamic object deserialized from NewtonSoft.Json.JObjcet.

    public static bool PropertyExists(dynamic obj, string name)
        {
            if (obj == null) return false;
            if (obj is ExpandoObject)
                return ((IDictionary)obj).ContainsKey(name);
            if (obj is IDictionary dict1)
                return dict1.ContainsKey(name);
            if (obj is IDictionary dict2)
                return dict2.ContainsKey(name);
            return obj.GetType().GetProperty(name) != null;
        }
    

提交回复
热议问题