c# - Return concrete type in abstract class -


we have abstract class baseclass (note generic arg!) method called me. me returns this.

if use me in concrete classes return type object. have cast result of me type working with.

how can achieve me returns actual type of this? in example type a?

public abstract class baseclass<tidentifier>{  public virtual object me{ { return this; } } }  public class a: baseclass<long> {  }  public class b: baseclass<long> {  }  public class controller{    public void somemethod(){        var = new a();        var b = new b();         var aobject = a.me; // of type object        var aobjectcasted = (a)aobject; // cast original         // how want        var aconcrete = a.me; // returns type    } } 

update

since people really, desperately (wink:-)) wish understand i'm trying do.

with nhibernate doing this:

var result = session.get<a>(idtolookup); 

in cases happens result isn't of type of type aproxy, due laze loading etc. if want cast result else: invalidcastexception because actual type of result isn't aproxy. , type can't casted. can cast type other type.

a workaround described here: http://sessionfactory.blogspot.be/2010/08/hacking-lazy-loaded-inheritance.html. that's me property in above examples comes in.

so result of type , not of type aproxy have this:

var result = (a)session.get<a>(idtolookup).me; 

note have cast me type if want read , know property of result.

my question: can rid of casting , adjust me property instantly return concrete type?

hope it's clear now.

you use interface on derived classes:

public interface istrongtypedme<t> {     t me(); } 

your derived classes become:

public class a: baseclass<long>, istrongtypedme<a> {     public new me()     {         return base.me() a;     } } 

this assuming can change a, of course.

update:

i understand issue (only had time read linked article now).

try using extension method casting this:

    public static treturntype as<treturntype,tidentifier>(this baseclass<tidentifier> proxyobject)         treturntype : class     {         return proxyobject.me treturntype;     } 

and you'd use like:

var result = session.get<a>(idtolookup).as<a,long>(); 

no changes a or b required.


Comments

Popular posts from this blog

Hatching array of circles in AutoCAD using c# -

ios - UITEXTFIELD InputView Uipicker not working in swift -

Python Pig Latin Translator -