我们如何检查动态粘土对象是否有一个属性? [英] How do we check whether a dynamic clay object has a property?
问题描述
我有一个动态对象,我认为是用Clay实现的 。它有两个可能的属性名称之一。我想使用哪个属性名称可用。以下不工作:
I have a dynamic object, that I think is implemented with Clay. It has one of two possible property names. I want to use which ever property name is available. The following doesn't work:
dynamic workItemPart = item.WorkItem; // is an Orchard.ContentManagement.ContentPart
var learnMore = workItemPart.LearnMore ?? workItemPart.LearnMoreField;
它会引发一个 Microsoft.CSharp.RuntimeBinder.RuntimeBinderException
:
不包含'LearnMore'的定义
does not contain a definition for 'LearnMore'
我们如何检查动态Clay对象是否具有属性? 在JavaScript中,例如,我们可以执行以下操作。
var workItemPart = {
LearnMoreField: "Sure"
}
console.log(workItemPart.LearnMore || workItemPart.LearnMoreField);
在C#中有什么简洁的Clay吗?
Is there anything this concise in C# with Clay?
相关:
是否使用Clay实现Orchard.ContentManagement.ContentPart?
https://twitter.com/bleroy/status/497078654405312512
推荐答案
您也可以使用索引方法:
You can also use the indexed approach:
var learnMore = workItemPart["LearnMore"] != null ?
workItemPart.LearnMore : workItemPart.LearnMoreField;
希望这有帮助。
UPDATE
我不知道为什么不会。两种方法都应该工作。
I'm not sure why it doesn't. Both methods should work.
dynamic New = new ClayFactory();
var person = New.Person();
person.skill = "Outstanding";
var talent = person.talent;
var talentTwo = person["talent"];
var skill = person.talent ?? person.skill;
Console.WriteLine(skill);
skill = person.skill ?? person.talent;
Console.WriteLine(skill);
也许是Orchard扔你一个曲球...
Perhaps it is Orchard throwing you a curveball ...
有趣的是,null-coalesce操作符不会正确处理第一个测试用例。但是,标准测试成功:
Interesting enough, the null-coalesce operator does not process the first test case correctly. However, the standard test succeeds:
skill = person.talent != null ? person.talent : person.skill;
Console.WriteLine(skill);
不知道此时给您的建议。
Not sure what to advise you at this point.
这篇关于我们如何检查动态粘土对象是否有一个属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!