C# generics: Simplify type signature -
this question has answer here:
if have generic item class looks this:
abstract class item<t> { } and container of items looks this:
class container<titem, t> titem : item<t> { } since titem depends on t, possible simplify type signature of container takes 1 type parameter? want this:
class container<titem> titem : item // doesn't work, because item takes type parameter { } so can instantiate follows:
class stringitem : item<string> { } var = new container<stringitem>(); var bad = new container<stringitem, string>(); the compiler should able deduce t string when titem stringitem, right? how make happen?
desired usage:
class myitem : item<string> { } container<myitem> container = getcontainer(); myitem item = container.getitem(0); item.mymethod();
this should want think. you're doing container<string> not container<stringitem> you've not included usage examples can't see being problem.
using system.collections.generic; namespace consoleapplication1 { class program { static void main(string[] args) { var mycontainer = new container<string>(); mycontainer.myitems = new list<item<string>>(); } } public class item<t> { } public class container<t> { // property on container show can use item<t> public list<item<t>> myitems { get; set; } } } how revised version:
using system.collections.generic; namespace consoleapplication1 { class program { static void main(string[] args) { var mycontainer = new container<stringitem>(); mycontainer.stronglytypeditem = new stringitem(); } } public class item<t> { } public class stringitem : item<string> { } // way hide this, can't figure out // (needs public because it's base type) // involves making container (or 3rd class??) // wrap private container, not inherit public class privatecontainer<titem, t> titem : item<t> { } // public interface public class container<t> : privatecontainer<item<t>, t> { // property on container show can use item<t> public t stronglytypeditem { get; set; } } }
Comments
Post a Comment