How to create a meaningful dynamic property?

A fictional example is here. Suppose I created a class called IODevice. This class already implements a structure that allows me to use it as follows:

        IODevice dio = new IODevice();

        try
        {
            dio.Pin["IsBirdInCageSensor"].Set();
            dio.Pin["KillBird"].Get();
            //dio.Pin["NonExistant"].Set(); //exception
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }

The pins here represent a series of IO lines in a digital I / O box, which can be high (1) or low (0).

I would like to use dynamic to call it like this:

        dio.Pins.KillBird.Get();

My class of IO devices looks like this right now, and as you noticed, I didn’t talk very much about how to implement a dynamic interface, except for using a dynamic keyword.

class IODevice
{
    public IODevice()
    {
        pin = new PinCollection();
        pin.Add(new Pin("IsBirdInCageSensor", 0));
        pin.Add(new Pin("KillBird", 1));
    }

    private PinCollection pin;
    public PinCollection Pin { get { return pin; } }

    public dynamic Pins { get; private set; }
}

Second question: what are the disadvantages of using such a design? (except for the lack of a hard type check that I don’t use at all)

+3
1

PinCollection, PinCollection IDynamicMetaObjectProvider. Pins PinCollection, Pin, , obj.Pins.KillBird ( GetMetaObject PinCollection).

, ExpandoObject :

private ExpandoObject _pins;
public dynamic Pins { get { return _pins; } }

ExpandoObject - , , . , PinCollection - : , .

+2

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


All Articles