Reputation: 121
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?
Upvotes: 2
Views: 102
Reputation: 78282
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>();
}
Upvotes: 2
Reputation: 53958
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.
Upvotes: 2