C # DynamicObject Listing for an arbitrary type

I am trying to write a good consumer API for protocol-based middleware in C #. ConfigManager.GetSection(...) returns an object, so I want to return a dynamic object that, when I click on the required type, causes a display.

Is there a way in C # 4 + to create a dynamic class that can handle a call if there is an explicit cast to it?

eg.

 MyConfig config = (MyConfig)ConfigurationManager.GetSection("some/section"); 

In this case, the dynamic object from the ConfigurationManager will be called by the application to perform some configuration magic (I solved this bit)

+4
source share
2 answers

Yes, DynamicObject has an override of TryConvert . When a DynamicObject subclass DynamicObject executed (or implicitly converted to a destination), TryConvert is called, and you can get dynamic call information from the binder parameter before returning the result.

Binder. The type property provides the type to which the object should be transformed. For example, for the expression (String) sampleObject in C # (CType (sampleObject, Type) in Visual Basic), where sampleObject is an instance of a class derived from the DynamicObject class, binder.Type returns a String type. The binder.Explicit property provides information about the type of conversion. This returns true for the explicit conversion and false for the implicit conversion.

+2
source

There are many projects that address your needs.

Take a look at AutoConfig , for example.

+1
source

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