generics - C# - Access property in inheriting class -


i'm trying access generic typed property in child class. in below example recreated problem. there workaround problem, or not possible? in advance!

edit: it's not possible declare collection a<model> or a<t>.

public abstract class model {     public int id { get; } }  public interface i<t> t: model {     icollection<t> results { get; } }  public abstract class { }  public class a<t> : a, i<t> t : model {     public icollection<t> results { get; } }  public class example {      a[] col;      void addsomemodels() {         col = new a[] {             new a<somemodel>(),             new a<someothermodel>()         }     }      void dosomethingwithcollection() {         foreach (var in col) {             // a.results not known @ point             // possible achieve functionality?         }     } } 

you can't intend without compromises.

first of all, need make interface i<t> covariant in t:

public interface i<out t> t : model {     ienumerable<t> results { get; } } 

the first compromise therefore t can output. icollection<t> isn't covariant in t you'd need change type of results ienumerable<t>.

once this, following type safe , therefore allowed:

public void dosomethingwithcollecion() {     var genericcol = col.oftype<i<model>>();      foreach (var in genericcol )     {         //a.results accessible.     } } 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -