Covariance with C#

后端 未结 2 402
孤独总比滥情好
孤独总比滥情好 2021-01-22 01:25

I met some interesting covariance problem in my c# code.

I have a generic Matrix class, and it\'s been instantiated for example Matrix

2条回答
  •  遥遥无期
    2021-01-22 01:52

    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());
    wrappers.Add(new Wrapper());
    wrappers.Add(new Wrapper());
    var visitor = new SerializationVisitor();//Create the operation you need to apply
    foreach (var wrapper in wrappers)
    {
        wrapper.Accept(visitor);
    }
    
    
    

    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]
    

    提交回复
    热议问题