c# - Why does this generic method call not match? -
i have address
class:
public class address { //some stuff }
and there's corresponding *wrapper
class enforce rules on how use address
class:
public class addresswrapper : iwrapped<address> { private address _wrapped; public address getwrapped() { return _wrapped; } //and more }
where iwrapped
defined as:
public interface iwrapped<t> { t getwrapped(); }
i have following generic class saving these entities (there other entities follow pattern of entity
, entitywrapper
):
public class genericrepository { private genericrepository() { } public static void add<t>(iwrapped<t> entity) { //do } public static void addlist<t>(ilist<iwrapped<t>> entities) { //do } }
and have test code:
[test] public void usegenericrepository() { addresswrapper addrw = new addresswrapper(); addrw.addrline1 = "x"; addrw.addrline2 = "y"; addrw.addrline3 = "z"; addrw.city = "starling city"; //this works expected genericrepository.add<address>(addrw); ilist<addresswrapper> addrlist = new list<addresswrapper>(); //fill addrlist //this gives error: best overloaded method match has invalid //arguments genericrepository.addlist<address>(addrlist); }
addresswrapped
of type iwrapped<address>
(i.e., implements it) , address
type parameter being given addlist
method, types should line up. know due limited knowledge of c# generics (familiar java generics), can't figure out what's wrong here --- should work.
this doesn't make difference, here's config:
- nhibernate 4.x
- .net framework (4.5)
this because of missing type variance of ilist<t>
. (ilist<int>
not ilist<object>
).
use ienumerable<t>
, because covariant:
public static void addlist<t>(ienumerable<iwrapped<t>> entities) { //do }
reason: if instance of list<addresswrapper>
, compiler doesn't know if compatible any possible implementation of ilist<iwrapped<t>>
. assume class implements iwrapped<t>
. wouldn't compatible when writing list. though don't write list in addlist
, compiler accepts compatible types. ienumerable<t>
cannot written, can variant.
not related question suggest use covariance own interface well:
public interface iwrapped<out t>
to make iwrapped<thing>
compatible iwrapped<specificthing>
.
msdn: https://msdn.microsoft.com/en-us/library/ee207183.aspx
Comments
Post a Comment