0

I've got a base class that I intend to use to create different types of classes that represent different types of work or actions:

    public abstract class BaseWork<T1, T2>
    {
        public event EventHandler<WorkStartedEventArgs>? WorkStarted;
        public event EventHandler<WorkEndedEventArgs>? WorkEnded;

        public abstract WorkResult<T1, T2> DoWork();
        public abstract WorkResult<T1, T2> DoWork<T3, T4>(WorkResult<T3, T4> previous);
        protected abstract WorkResult<T1, T2> WorkDone();

        protected virtual void OnWorkStarted(WorkStartedEventArgs e) => WorkStarted?.Invoke(this, e);
        protected virtual void OnWorkEnded(WorkEndedEventArgs e) => WorkEnded?.Invoke(this, e);
    }

An example of such a class is the "RotateScrewConveyour" class which inherits from the base class above. (This will set a pin to high, to start a motor).

I intend to create a container which is composed of objects whose class inherits from the base class, which will then be used to step by step execute a series of actions. Some actions may depend on the result of previous actions.

What has me a bit stumped is, I am not sure how to collect the objects created by the classes that inherit from this base class. And what if I in the future want to create a new base class that is idental to the current one, but with a different amount of type parameters?

In summary, how can I insert objects of multiple different (but almost identical) generic classes, with different type parameters, into one container? I've thought about using the command pattern, but I'm not quite sure how I'd make that work in my case.

6
  • You can use boxing and add them to a collection of object. Then as you iterate you can conditionally unbox them based on their type. learn.microsoft.com/en-us/dotnet/csharp/programming-guide/types/… Nov 26, 2019 at 14:05
  • You could create an interface and implement it into the base class, then have a collection of that interface?
    – A Friend
    Nov 26, 2019 at 14:08
  • I've thought about creating an interface and implementing it into the base class, it just seems wrong to me to create an instance for the sole purpose of being able to stuff my objects into a container. I'm hoping there's a more elegant way Nov 26, 2019 at 14:10
  • @bhmahler I'm not sure if I like this solution, I've thought about using is to determine the type, but this could potentially lead to a large amount of if statements. Couldn't it? Nov 26, 2019 at 14:12
  • Potentially, but if you want to have a collection of multiple types, they all must either implement the same interface or base class. If that is not the case, boxing and unboxing makes sense. Nov 26, 2019 at 14:17

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.