如何检查一个属性是否存在于c#中的dynamic匿名types?

我有一个匿名types的对象,我收到一个方法,我想检查该对象上存在的属性的dynamic。

.... var settings = new { Filename="temp.txt", Size=10 } ... function void Settings(dynamic settings) { var exists = IsSettingExist(settings,"Filename") } 

我将如何实现IsSettingExist?

  public static bool IsPropertyExist(dynamic settings, string name) { if (settings is ExpandoObject) return ((IDictionary<string, object>)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")); 

输出:

  True False 
 public static bool HasProperty(dynamic obj, string name) { Type objType = obj.GetType(); if (objType == typeof(ExpandoObject)) { return ((IDictionary<string, object>)obj).ContainsKey(name); } return objType.GetProperty(name) != null; } 

如果你可以控制创build/传递设置对象,我build议使用ExpandoObject来代替。

 dynamic settings = new ExpandoObject(); settings.Filename = "asdf.txt"; settings.Size = 10; ... function void Settings(dynamic settings) { if ( ((IDictionary<string, object>)settings).ContainsKey("Filename") ) .... do something .... } 

这是为我工作 – :

  public static bool IsPropertyExist(dynamic dynamicObj, string property) { try { var value=dynamicObj[property].Value; return true; } catch (RuntimeBinderException) { return false; } } 

合并和解决来自Serj-TM和user3359453的答案,以便与ExpandoObject和DynamicJsonObject一起使用。 这对我有用。

 public static bool HasPropertyExist(dynamic settings, string name) { if (settings is System.Dynamic.ExpandoObject) return ((IDictionary<string, object>)settings).ContainsKey(name); if (settings is System.Web.Helpers.DynamicJsonObject) try { return settings[name] != null; } catch (KeyNotFoundException) { return false; } return settings.GetType().GetProperty(name) != null; } 

使用reflection,这是我使用的function:

 public static bool doesPropertyExist(dynamic obj, string property) { return ((Type)obj.GetType()).GetProperties().Where(p => p.Name.Equals(property)).Any(); } 

然后..

 if (doesPropertyExist(myDynamicObject, "myProperty")){ // ... } 

上面的解决scheme都不适用于来自Json dynamic ,但是我通过将抛出的exceptiontypes( KeyNotFoundException而不是RuntimeBinderException )更改为实际工作的东西来Try catch使用Try catch (by @ user3359453)来转换它。

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

在这里输入图像说明

希望这可以为你节省一些时间。