Covariance with C# -


i met interesting covariance problem in c# code.

i have generic matrix<t> class, , it's been instantiated example matrix<int>, matrix<object> , matrix<apple>.

for business logic, i've wrapped them generic wrapper<t>. wrapper implements non-generic inongenericwrapper interface. so, have wrapper<int>, wrapper<object> , wrapper<apple>.

my problem is: define container 3 wrappers. can't list<wrapper<object>>, because can't insert wrapper<int> collection. can't list<inongenericwrapper>, because inside foreach, access generic matrix<t> parameter.

cheesy part: wrappers (de-)serialized definite type: myserializer<wrapper<apple>>.serialize(_myinstanceofwrappedapple).

i think it's clear avoid huge switches of typeof when serializing..

what possible workarounds? i'm kinda stuck.

thanks in advance,

recently i've come across such limitation , implemented variation of visitor pattern (may abuse of it). helped me solve problem.

i'm no architect, developer. pardon me if abusing design pattern, sure help.

with provided information created mocks of classes , applied visitor pattern follows.

public class matrix<t> {     public t obj { get; set; } }  public interface inongenericwrapper {     void wrap();     void accept(ivisitor visitor); }  public class wrapper<t> : inongenericwrapper {     public matrix<t> 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>(t element); }  public class serializationvisitor : ivisitor {     public void visit<t>(t element)     {         new serializer<t>().serialize(element);     } }  public class serializer<t> {     public stream serialize(t objecttoserialize)     {         console.writeline("serializing {0}", objecttoserialize);         //your serialization logic here         return null;     } } 

how use:

list<inongenericwrapper> wrappers = new list<inongenericwrapper>(); wrappers.add(new wrapper<object>()); wrappers.add(new wrapper<string>()); wrappers.add(new wrapper<int>()); var visitor = new serializationvisitor();//create operation need apply foreach (var wrapper in wrappers) {     wrapper.accept(visitor); } 

all you've create new visitor each operation need perform.

here demo outputs

serializing wrapper`1[system.object] serializing wrapper`1[system.string] serializing wrapper`1[system.int32] 

Comments

Popular posts from this blog

java - Intellij Synchronizing output directories .. -

git - Initial Commit: "fatal: could not create leading directories of ..." -