簡體   English   中英

更改System.Dynamic.ExpandoObject的默認行為

[英]Change System.Dynamic.ExpandoObject default behavior


我使用System.Dynamic.ExpandoObject()創建了一個動態對象,現在在某些情況下某些屬性可能不存在,如果嘗試以這種方式訪問​​這些屬性

myObject.undefinedProperties;

對象的默認行為是拋出異常

'System.Dynamic.ExpandoObject' does not contain a definition for 'undefinedProperties'

有可能改變這種行為並在這種情況下返回空值嗎?

如果您可以使用DynamicObject替換ExpandoObject ,您可以編寫滿足您要求的自己的類:

public class MyExpandoReplacement : DynamicObject
{
    private Dictionary<string, object> _properties = new Dictionary<string, object>();
    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        if (!_properties.ContainsKey(binder.Name))
        {
            result = GetDefault(binder.ReturnType);
            return true;
        }

        return _properties.TryGetValue(binder.Name, out result);
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        this._properties[binder.Name] = value;
        return true;
    }

    private static object GetDefault(Type type)
    {
        if (type.IsValueType)
        {
            return Activator.CreateInstance(type);
        }
        return null;
    }
}

用法:

dynamic a = new MyExpandoReplacement();
a.Sample = "a";

string samp = a.Sample; // "a"
string samp2 = a.Sample2; // null

ExpandoObject繼承IDictionary <string,object>,因此您可以檢查對象是否具有這樣的“undefinedProperties”

if (((IDictionary<string, object>)myObject).ContainsKey("undefinedProperties"))
{
    // Do something
}

您可以在ExpandoObject中測試屬性的存在,請參閱此處的ExpandoObject中的Detect屬性

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM