c# - Working around lack of partial generic type inference with constraints -


i have interface (which used repositories) has member:

t findbyid<t, tid>(tid id)     t : class, ientity<tid>     tid : iequatable<tid>; 

this allows caller specify entity type (t) , type of it's id field (tid). implementor of interface find entities of type t , use id parameter filter them according id (which defined on ientity<tid>).

currently i'm calling this:

int id = 123; var myapproval = partsdc.findbyid<approval, int>(id); 

ideally i'd this:

int id = 123; var myapproval = partsdc.findbyid<approval>(id); 

i've read answers question:

partial generic type inference possible in c#?

i understand can't syntax want, can close. can't quite setup right in case though because of generic parameter constraints.

here's have far:

public class findidwrapper<t> t : class {     public readonly idatacontext invokeon;      public findidwrapper(idatacontext invokeon)     {         invokeon = invokeon;     }      t byid<tid>(tid id) tid : iequatable<tid>     {         return invokeon.findbyid<t, tid>(id);     } }  public static class datacontextextensions {     public static findidwrapper<t> find<t>(this idatacontext datacontext) t : class, ientity     {         return new findidwrapper<t>(datacontext);     } } 

the compilation error is:

the type 't' cannot used type parameter 't' in generic type or method 'partslegislation.repository.idatacontext.findbyid<t,tid>(tid)'. there no implicit reference conversion 't' 'partslegislation.repository.ientity<tid>'.

i understand it's saying because t in wrapper class constrained reference type, findbyid function wants ientity<tid>, can't tid in method (otherwise i'm @ square one).

how can around issue (or can't i)?

that can't work usual way around because can't convince compiler of tid constraint after fact. can, however, reverse sequence, i.e.

var obj = byid(id).find<sometype>(); 

not elegant, works. implementation:

public finder<tid> byid<tid>(tid id) tid : iequatable<tid> {     return new finder<tid>(this, id); } public struct finder<tid> tid : iequatable<tid> {     private readonly yourparent parent;     private readonly tid id;     internal finder(yourparent parent, tid id)     {         this.id = id;         this.parent = parent;     }     public t find<t>() t : class, ientity<tid>     {         return parent.findbyid<t, tid>(id);     } } 

caveat: easier tell both parameter types explicitly.


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 -