c# - Cast boxed object to typeof(object) -


i have following poco classes

public interface iobject {     guid uid { get; set; } }  public class boo : iobject {     public guid uid { get; set; }     public string name { get; set; } }  public class foo : iobject {     public guid uid { get; set; }     public string name { get; set; } } 

i trying write generic method insert type of object database type inherit iobject. using following method (with servicestackormlite underneath):

public interface idataaccess {     idbconnection getconnection();      boolean insertobject<t>(t newobj, idbconnection connection) t : idataobject, new(); } 

trying insert each object separately works follow :

public static boolean addfoo(this foo foo) {     // dataprovider initiated using implementation of idataaccess     return dataprovider.insertobject(foo, dataprovider.getconnection()); } 

question :

i trying use following method valid 1 both fails. syntax wrong consider pseudo code. how can acheive that? obj boxed foo or boo instance

public static boolean addobject(this iobject obj) {     type objecttype = obj.gettype();     return dataprovider.insertobject(obj objecttype, dataprovider.getconnection()); } 

i'm making assumption iobject / idataobject same thing - otherwise hard see how call ever work. so, easiest thing make caller supply t:

public static bool addobject<t>(this t obj) t : iobject, new() {     return dataprovider.insertobject<t>(obj, dataprovider.getconnection()); } 

however, not workable (the caller might only know iobject), in case can runtime worry it:

public static bool addobject(this iobject obj) {     return dataprovider.insertobject((dynamic)obj, dataprovider.getconnection()); } 

the other option reflection via makegenericmethod / invoke - messy , slow.

frankly, advocate non-generic api here. reflection , generics not make friends. however, servicestack may not give luxury, in case, dynamic approach convenient option here.


Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -