检查一个属性是否存在于C#Expando类中 [英] check to see if a property exists within a C# Expando class

查看:122
本文介绍了检查一个属性是否存在于C#Expando类中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想看一个属性是否存在于C#Expando Class中。



非常像 hasattr 函数在python中。我想要这个等价于...的



这样的东西...

  if(HasAttr(model,Id))
{
#使用model.Id
}


解决方案

尝试:

  dynamic yourExpando = new ExpandoObject(); 
if(((IDictionary< string,Object>)yourExpando).ContainsKey(Id))
{
//具有属性...
}

ExpandoObject显式实现 IDictionary< string,Object> ,其中Key是属性名称。然后,您可以检查该字典是否包含该键。你也可以写一个小帮手方法,如果你需要经常做这种检查:

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

使用如下:



pre> if(HasAttr(yourExpando,Id))
{
//有属性...
}


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
}

解决方案

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...
}

这篇关于检查一个属性是否存在于C#Expando类中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆