动态对象 - 如何判断属性是否被定义? [英] Dynamic Object - How to tell if a property is defined?

查看:110
本文介绍了动态对象 - 如何判断属性是否被定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个动态对象,如下所示:

I have a dynamic object that looks as follows:

this.ChartDetails.Chart

'图表'是动态的。我想看看图表中是否存在动态属性,名为LeftYAxis。在动态对象上执行此操作的最佳方式是什么?

'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?

我不认为这与如何检测ExpandoObject上是否存在属性?,因为它不讨论动态对象的最佳方法。

I don't think this is a duplicate of How to detect if a property exists on an ExpandoObject? 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)
{ }

首先在运行时会发生什么。 (当您访问某个属性时,只有当第一次机会异常被对象的覆盖 DynamicObject TryGetMember TrySetMember

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

某些对象(如 ExpandoObject )实际上是字典,你可以直接检查它们如下:

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");

基本上:不知道实际类型 ChartDetails.Chart 是(如果它是一个 ExpandoObject 对象 DynamicObject 的子类的简单ol'子类除了try /如果你写了 ChartDetails Chart 的代码,或者可以访问源代码,你可以确定什么方法存在的对象和使用thos e来检查。

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屋!

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