动态对象 - 如何判断一个属性定义? [英] Dynamic Object - How to tell if a property is defined?
问题描述
我有一个动态的对象,如下所示:
this.ChartDetails.Chart
图表是动态的。我想看看在名为LeftYAxis图表中的动态特性。什么是做这个动态对象的最佳方式?
我不认为这是的如何检测是否在C#中的动态物体上存在的属性?因为它不讨论为动态对象做到这一点的最好方法。
布尔isDefined = FALSE;
轴对象= NULL;
试
{
轴= this.ChartDetails.Chart.LeftYAxis;
isDefined = TRUE;
}
赶上(RuntimeBinderException)
{}
这是什么摆在首位在运行时发生的。 (当您访问属性动态一件事情,当一个第一次机会异常被通过的对象的覆盖处理,只发生 DynamicObject
的 TryGetMember
和 TrySetMember
有些对象(如 ExpandoObject
)实际上是引擎盖下字典,你可以直接检查它们如下:
布尔isDefined =( (IDictionary的<字符串对象>)this.ChartDetails.Chart)
.ContainsKey(LeftYAxis);
基本上是:不知道什么的实际的类型 ChartDetails.Chart
是(如果它是一个 ExpandoObject
对象
或子类的纯醇'子 DynamicObject
)有除了尝试没办法/赶上上面。如果你写的代码为 ChartDetails
和图
或访问源代码,你可以决定哪些方法存在的对象,并使用这些检查。
I have a dynamic object that looks as follows:
this.ChartDetails.Chart
'Chart' is dynamic. I want to see if a dynamic property exists on Chart named LeftYAxis. What is the best way to do this on dynamic objects?
I don't think this is a duplicate of how to detect if a property exists on a dynamic object in C#? because it doesn't discuss the best method to do this for dynamic objects.
bool isDefined = false;
object axis = null;
try
{
axis = this.ChartDetails.Chart.LeftYAxis;
isDefined = true;
}
catch(RuntimeBinderException)
{ }
This is what happens at runtime in the first place. (When you access a property the 'dynamic' piece of things only happens when a first-chance exception gets handled by the object's override of DynamicObject
's TryGetMember
and TrySetMember
Some objects (like ExpandoObject
) are actually dictionaries under the hood and you can check them directly as follows:
bool isDefined = ((IDictionary<string, object>)this.ChartDetails.Chart)
.ContainsKey("LeftYAxis");
Basically: without knowing what actual type ChartDetails.Chart
is (if it's an ExpandoObject
a plain ol' subclass of object
or a subclass of DynamicObject
) there's no way besides the try/catch above. If you wrote the code for ChartDetails
and Chart
or have access to the source code you can determine what methods exist for the object and use those to check.
这篇关于动态对象 - 如何判断一个属性定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!