I met some interesting covariance problem in my c# code.
I have a generic Matrix
class, and it\'s been instantiated for example Matrix
Recently I've come across such limitation and I implemented a variation of Visitor Pattern (may be abuse of it). But that helped me to solve the problem.
I'm no architect, just a developer. So pardon me if am abusing the design pattern, but sure this will help.
With provided information I created mocks of your classes and applied visitor pattern as follows.
public class Matrix
{
public T Obj { get; set; }
}
public interface INonGenericWrapper
{
void Wrap();
void Accept(IVisitor visitor);
}
public class Wrapper : INonGenericWrapper
{
public Matrix Matrix { get; private set; }
public void Wrap()
{
//Your domain specific method
}
public void Accept(IVisitor visitor)
{
visitor.Visit(this);
}
}
public interface IVisitor
{
void Visit(T element);
}
public class SerializationVisitor : IVisitor
{
public void Visit(T element)
{
new Serializer().Serialize(element);
}
}
public class Serializer
{
public Stream Serialize(T objectToSerialize)
{
Console.WriteLine("Serializing {0}", objectToSerialize);
//Your serialization logic here
return null;
}
}
How to use:
List wrappers = new List();
wrappers.Add(new Wrapper
All you've to do is create a new visitor for each operation you need to perform.
Here is the Demo which outputs
Serializing Wrapper`1[System.Object]
Serializing Wrapper`1[System.String]
Serializing Wrapper`1[System.Int32]