本文介绍了.NET DynamicObject实施,对于缺失的属性返回null,而不是一个RunTimeBinderException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够做类似如下:

I'd like to be able to do something like the following:

dynamic a = new ExpandoObject();
Console.WriteLine(a.SomeProperty ?? "No such member");



但抛出

but that throws

RunTimeBinderException: 'System.Dynamic.ExpandoObject' does not contain a definition for 'Throw'



的定义

你知道DynamicObject的实现,将返回null失踪的定义,或者对如何创建一个教程?非常感谢!

Do you know of an implementation of DynamicObject that would return null for missing definitions, or a tutorial on how to create one? Many thanks!

推荐答案

这样呢?

using System;
using System.Collections.Generic;
using System.Dynamic;

public class NullingExpandoObject : DynamicObject
{
    private readonly Dictionary<string, object> values
        = new Dictionary<string, object>();

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        // We don't care about the return value...
        values.TryGetValue(binder.Name, out result);
        return true;
    }

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

class Test
{
    static void Main()
    {
        dynamic x = new NullingExpandoObject();
        x.Foo = "Hello";
        Console.WriteLine(x.Foo ?? "Default"); // Prints Hello
        Console.WriteLine(x.Bar ?? "Default"); // Prints Default
    }
}



我希望真正的 ExpandoObject 是相当比这更复杂,但如果这是你所需要的...

I expect the real ExpandoObject is rather more sophisticated than this, but if this is all you need...

这篇关于.NET DynamicObject实施,对于缺失的属性返回null,而不是一个RunTimeBinderException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 12:54