casting a base generic class from a derived generic class in C# -


i need find way retrieve properties instance of generic class, generic argument type derived class. example:

class  {     public int data; }  class b : class { }  class c : class { }  class d : class { }  . . .  class g<t>  {     t field }  main() {     object t = callouterservice(); } 

given t instance of g instantiated 1 of deriving classes, there way access data field without trying cast deriving classes?

*edited - 1. data field public 2. classes a, b, c... g not handled code, interfaces external service. can't edit them in way...

through covariance could:

class {     public int data; }  class b : { }  class c : { }  class d : { }  interface ig<out t> {     t field { get; } }  class g<t> : ig<t> {     public t field { get; set; } } 

and then:

g<d> gd = new g<d> { field = new d { data = 5 } };  ig<a> ga = gd; int data = ga.field.data; // 5 

note can read field property, not write it! , covariance interfaces (for reason had define ig<t> interface , use access field property)


Comments

Popular posts from this blog

How has firefox/gecko HTML+CSS rendering changed in version 38? -

javascript - Complex json ng-repeat -

jquery - Cloning of rows and columns from the old table into the new with colSpan and rowSpan -