【发布时间】:2012-08-16 04:26:19
【问题描述】:
我想查看 C# Expando 类中是否存在属性。
很像python中的hasattr函数。我想要 hasattr 的 c# 等号。
这样的……
if (HasAttr(model, "Id"))
{
# Do something with model.Id
}
【问题讨论】:
标签: c# dynamic expandoobject
我想查看 C# Expando 类中是否存在属性。
很像python中的hasattr函数。我想要 hasattr 的 c# 等号。
这样的……
if (HasAttr(model, "Id"))
{
# Do something with model.Id
}
【问题讨论】:
标签: c# dynamic expandoobject
试试:
dynamic yourExpando = new ExpandoObject();
if (((IDictionary<string, Object>)yourExpando).ContainsKey("Id"))
{
//Has property...
}
ExpandoObject 显式实现 IDictionary<string, Object>,其中 Key 是属性名称。然后,您可以检查字典是否包含该键。如果你需要经常做这种检查,你也可以写一个小辅助方法:
private static bool HasAttr(ExpandoObject expando, string key)
{
return ((IDictionary<string, Object>) expando).ContainsKey(key);
}
然后像这样使用它:
if (HasAttr(yourExpando, "Id"))
{
//Has property...
}
【讨论】:
根据 vcsjones 的回答,它会更好:
private static bool HasAttr(this ExpandoObject expando, string key)
{
return ((IDictionary<string, Object>) expando).ContainsKey(key);
}
然后:
dynamic expando = new ExpandoObject();
expando.Name = "Test";
var result = expando.HasAttr("Name");
【讨论】: