Organizing and Calling C # Methods Dynamically

Relatively new to C #, which is looking for a way to “best practice”:

I have a class (sensor) with public methods, such as "CommunicationStart", "DoThing1", "DoThing2".

Before calling these methods, the class is configured using the Model sensor

Based on the model, public methods must use different code paths. If I did this statically, switching to a model in every public method would do the trick.

I want to do this dynamically for long-term support. What is the “right” approach to wrapping dynamically loaded code in each of the public methods? Reflection? Delegates Where should the dynamically loaded functions be located? Should they be in the same class as their publicly available wrappers, or live in a new class?

I am looking more for the “right” approach and organization, and not for the syntax, since I can figure it out myself. Many thanks!

+4
source share
1 answer

I hope I understood your question correctly. Here's how I could do to create an extensible system for both common methods and sensor implementations:

( ):

, Reflection, , , ISensorMethod ( ). . , execute() , , string Key { get; }. , ( ).

- (, ) List<ISensorMethod> .

"":

: , "Sensor" "ISensor". . Sensor ( ), IMethodCaller, .

public interface IMethodCaller
{
   void CallMethodByKey(string key);
}

:

public class ElectricSensor : Sensor
{
   public ElectricSensor(IMethodCaller caller): base(caller)
   {
   }

   public void CommunicationStart()
   {
      base.Caller.CallMethodByKey("START_COMMON");
      base.Caller.CallMethodByKey("INITIALIZE_ELECTRIC");
   }

  // (...) 
}

Sensor factory... . Reflection , , , , ... ( , ).

,

+1

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


All Articles