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

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

    None of the solutions above worked for dynamic that comes from Json, I however managed to transform one with Try catch (by @user3359453) by changing exception type thrown (KeyNotFoundException instead of RuntimeBinderException) into something that actually works...

    public static bool HasProperty(dynamic obj, string name)
        {
            try
            {
                var value = obj[name];
                return true;
            }
            catch (KeyNotFoundException)
            {
                return false;
            }
        }
    

    Hope this saves you some time.

提交回复
热议问题