check to see if a property exists within a C# Expando class

时光毁灭记忆、已成空白 提交于 2020-01-03 08:30:11

问题


I would like to see if a property exist in a C# Expando Class.

much like the hasattr function in python. I would like the c# equalant for hasattr.

something like this...

if (HasAttr(model, "Id"))
{
  # Do something with model.Id
}

回答1:


Try:

dynamic yourExpando = new ExpandoObject();
if (((IDictionary<string, Object>)yourExpando).ContainsKey("Id"))
{
    //Has property...
}

An ExpandoObject explicitly implements IDictionary<string, Object>, where the Key is a property name. You can then check to see if the dictionary contains the key. You can also write a little helper method if you need to do this kind of check often:

private static bool HasAttr(ExpandoObject expando, string key)
{
    return ((IDictionary<string, Object>) expando).ContainsKey(key);
}

And use it like so:

if (HasAttr(yourExpando, "Id"))
{
    //Has property...
}



回答2:


According to vcsjones answer it will be even nicer to:

private static bool HasAttr(this ExpandoObject expando, string key)
{
    return ((IDictionary<string, Object>) expando).ContainsKey(key);
}

and then:

dynamic expando = new ExpandoObject();
expando.Name = "Test";

var result = expando.HasAttr("Name");


来源:https://stackoverflow.com/questions/12044465/check-to-see-if-a-property-exists-within-a-c-sharp-expando-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!