How to detect if a property exists on an ExpandoOb

2019-01-04 18:31发布

In javascript you can detect if a property is defined by using the undefined keyword:

if( typeof data.myProperty == "undefined" ) ...

How would you do this in C# using the dynamic keyword with an ExpandoObject and without throwing an exception?

10条回答
Rolldiameter
2楼-- · 2019-01-04 19:06

I wanted to create an extension method so I could do something like:

dynamic myDynamicObject;
myDynamicObject.propertyName = "value";

if (myDynamicObject.HasProperty("propertyName"))
{
    //...
}

... but you can't create extensions on ExpandoObject according to the C# 5 documentation (more info here).

So I ended up creating a class helper:

public static class ExpandoObjectHelper
{
    public static bool HasProperty(ExpandoObject obj, string propertyName)
    {
        return ((IDictionary<String, object>)obj).ContainsKey(propertyName);
    }
}

To use it:

// If the 'MyProperty' property exists...
if (ExpandoObjectHelper.HasProperty(obj, "MyProperty"))
{
    ...
}
查看更多
叼着烟拽天下
3楼-- · 2019-01-04 19:09

Try this one

public bool PropertyExist(object obj, string propertyName)
{
 return obj.GetType().GetProperty(propertyName) != null;
}
查看更多
smile是对你的礼貌
4楼-- · 2019-01-04 19:10

This extension method checks for the existence of a property and then returns the value or null. This is useful if you do not want your applications to throw unnecessary exceptions, at least ones you can help.

    public static object Value(this ExpandoObject expando, string name)
    {
        var expandoDic = (IDictionary<string, object>)expando;
        return expandoDic.ContainsKey(name) ? expandoDic[name] : null;
    }

If can be used as such :

  // lookup is type 'ExpandoObject'
  object value = lookup.Value("MyProperty");

or if your local variable is 'dynamic' you will have to cast it to ExpandoObject first.

  // lookup is type 'dynamic'
  object value = ((ExpandoObject)lookup).Value("PropertyBeingTested");
查看更多
SAY GOODBYE
5楼-- · 2019-01-04 19:10
(authorDynamic as ExpandoObject).Any(pair => pair.Key == "YourProp");
查看更多
登录 后发表回答