Implementing the dynamic capabilities of an object without inheriting DynamicObject?

Now I have a class that extends DynamicObject and overrides TryGetMember.

public class FieldCollection : DynamicObject, ICollection<Field>, ISerializable
{
    ...

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        var field = _inner.TryGetField(binder.Name);

        result = field == null ? null : field.Value;
        return true;
    }

    ...
}

dynamic fields = new FieldCollection();
Console.WriteLine(fields.Foo);

This works fine, but I am forced to extend DynamicObject, which means that I cannot extend anything else. Is it possible to do this without the DynamicObject extension?

+3
source share
2 answers

You can implement it IDynamicMetaObjectProvideryourself. This is a lot more work .

+4
source

You can delegate to a child DynamicObject, for example, this answer (which starts with @Lee's answer, but with extra work) to the duplicate SO question.

+1

Source: https://habr.com/ru/post/1793880/


All Articles