有没有办法在动态/ expando中执行链式空检查?

问题描述 投票:2回答:2

C#有用的qazxsw poi。很好地解释了qazxsw poi。

当我的对象是动态/ expando对象时,我想知道是否可以像这样进行类似的检查。我来告诉你一些代码:

鉴于此类层次结构

Null Conditional Operator

如果我执行这种链式空检查,它的工作原理

this answer

现在,我将尝试使用动态(ExpandoObject)重现此行为

public class ClsLevel1
{
    public ClsLevel2 ClsLevel2 { get; set; }
    public ClsLevel1()
    {
        this.ClsLevel2 = new ClsLevel2(); // You can comment this line to test
    }        
}

public class ClsLevel2
{
    public ClsLevel3 ClsLevel3 { get; set; }
    public ClsLevel2()
    {
        this.ClsLevel3 = new ClsLevel3();
    }       
}

public class ClsLevel3
{
    // No child
    public ClsLevel3()
    {
    }
}

有没有办法用动力学模拟这种行为?我的意思是,检查一长串成员中的空值?

c# .net dynamic expandoobject
2个回答
4
投票

如果您想以更自然的方式支持它,您可以从DynamicObject继承并提供自定义实现:

ClsLevel1 levelRoot = new ClsLevel1();
if (levelRoot?.ClsLevel2?.ClsLevel3 != null)
{
     // will enter here if you DO NOT comment the content of the ClsLevel1 constructor
}
else
{
     // will enter here if you COMMENT the content of the ClsLevel1 
}

测试:

dynamic dinRoot = new ExpandoObject();
dynamic DinLevel1 = new ExpandoObject();
dynamic DinLevel2 = new ExpandoObject();
dynamic DinLevel3 = new ExpandoObject();

dinRoot.DinLevel1 = DinLevel1;
dinRoot.DinLevel1.DinLevel2 = DinLevel2;
//dinRoot.DinLevel1.DinLevel2.DinLevel3 = DinLevel3; // You can comment this line to test

if (dinRoot?.DinLevel1?.DinLevel2?.DinLevel3 != null)
{
     // Obviously it will raise an exception because the DinLevel3 does not exists, it is commented right now.
}

输出将是“它工作!”。由于Boo不存在,我们得到一个空引用,以便Null条件运算符可以工作。

我们在这里做的是每次找不到属性时返回对TryGetMember的输出参数的空引用,并且我们总是返回true。


0
投票

编辑:修复,因为ExpandoObjects和扩展方法不能很好地协同工作。略微不太好,但希望仍然可用。

助手方法:

class MyExpando : DynamicObject
    {
        private readonly Dictionary<string, object> _dictionary = new Dictionary<string, object>();

        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            var name = binder.Name.ToLower();
            result = _dictionary.ContainsKey(name) ? _dictionary[name] : null;
            return true;
        }

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

用法:

 private static void Main(string[] args)
        {
            dynamic foo = new MyExpando();
            if (foo.Boo?.Lol ?? true)
            {
                Console.WriteLine("It works!");
            }
            Console.ReadLine();
        }
© www.soinside.com 2019 - 2024. All rights reserved.