简体   繁体   中英

Create instance of generic class c#

So here is the code:

  public interface IObserver<T> where T : StackEventData<T>
    {
        void HandleEvent(StackEventData<T> eventData);
    }

    public class Observer<T> : IObserver<T> where T : StackEventData<T>, new()
    {
        public StringBuilder Log = new StringBuilder();

        public void HandleEvent(StackEventData<T> eventData)
        {
            Log.Append(eventData);
        }
    }

public class StackOperationsLogger
    {
        private readonly Observer<T> observer = new Observer<T>();
    }

I need to initialize Observer observer in StackOperationsLogger without making StackOperationsLogger generic. Any suggestions?

Provided that you have some class definitions like the following:

public class ConcreteType : StackEventData<ConcreteType>
{
}

public class StackEventData<T>
{
}

You could try this:

public class StackOperationsLogger
{
    private Observer<ConcreteType> observer = new Observer<ConcreteType>();
}

Apparently you have to design your class correspondingly. Above just highlighted how should be the "name" of the classes and what is expected from the ConcreteType class you will define -bad name..you have to change also this.

One huge problem is the original generic definition of the interface.

public interface IObserver<T> where T : StackEventData<T>

Since the type constraint is defined recursively you can't use it in the way you want. Essentially type T has to be something like this: StackEventData<StackEventData<StackEventData<StackEventData<T>>>> etc. I don't think that is what you are looking for.

I have a feeling that this is what you are looking for.

public interface IObserver<T> 
{
    void HandleEvent(StackEventData<T> eventData);
}

public class Observer<T> : IObserver<T>
{
    public StringBuilder Log = new StringBuilder();

    public void HandleEvent(StackEventData<T> eventData)
    {
        Log.Append(eventData);
    }
}

public class StackOperationsLogger
{
    private readonly Observer<DataObject> observer = new Observer<DataObject>();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM