Generic extension method with an interface contraint -
i have made generic extension method (i.e asxml) still want constraint interface (ixmlable) on of classes.
as have introduced constraint, of methods arguing me.
one of methods returing list<interest> , compiler says:
the type 'system.collections.generic.list' cannot used type parameter 't' in generic type or method 'mywebapp.entities.extension.asxml(t)'. there no implicit reference conversion 'system.collections.generic.list' 'mywebapp.interfaces.ixmlable'.
this class:
public class person : ixmlable { public string name { get; set; } public list<interest> interests { get; set; } // interest class implements ixmlable } my extension method looks this:
public static class extension { public static string asxml<t>(this t entity) t : ixmlable { return makeitxml(entity); } } this method:
return mymethodthatreturnsalistofpersons().asxml();
you need like
return mymethodthatreturnsalistofpersons().select(p => p.asxml()).tolist(); assuming mymethodthatreturnsalistofpersons returns list<person> , want create list<string> containing xml.
this because list<t> not implement ixmlable interface, have manually projection on each person element in list.
if need lot create extension method:
public static list<string> asxmllist<t>(this ienumerable<t> seq) t : ixmlable { return seq.select(i => i.asxml()).tolist(); } so code be:
return mymethodthatreturnsalistofpersons().asxmllist();
Comments
Post a Comment