gpt4 book ai didi

c# - 检查属性是否存在于 C# Expando 类中

转载 作者:太空狗 更新时间:2023-10-29 18:07:32 25 4
gpt4 key购买 nike

我想查看 C# Expando 类中是否存在某个属性。

很像 hasattr python中的函数。我想要 hasattr 的 c# equalant。

像这样的……

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

最佳答案

尝试:

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

关于c# - 检查属性是否存在于 C# Expando 类中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12044465/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com