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

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

      public static bool IsPropertyExist(dynamic settings, string name)
      {
        if (settings is ExpandoObject)
          return ((IDictionary)settings).ContainsKey(name);
    
        return settings.GetType().GetProperty(name) != null;
      }
    
      var settings = new {Filename = @"c:\temp\q.txt"};
      Console.WriteLine(IsPropertyExist(settings, "Filename"));
      Console.WriteLine(IsPropertyExist(settings, "Size"));
    

    Output:

     True
     False
    

提交回复
热议问题