Is it possible to define a default generic type?
public class StuffDoer<T>
{
// do stuff
}
I want that this is always of type string, so instead of doing this:
StuffD开发者_StackOverflow中文版oer<string> stuffer = new StuffDoer<string>();
I want to be able to do this:
StuffDoer stuffer = new StuffDoer();
and if I need a StuffDoer of type int, just define that with generics.
StuffDoer<int> stuffer = new StuffDoer<int>();
Is this possible?
Rather than using subclasses where there's no real specialization going on, I would suggest using a separate static "factory" class:
public static class StuffDoer
{
public static StuffDoer<string> Create()
{
return new StuffDoer<string>();
}
public static StuffDoer<T> Create<T>()
{
return new StuffDoer<T>();
}
public static StuffDoer<T> Create<T>(T item)
{
StuffDoer<T> ret = new StuffDoer<T>();
ret.Add(item); // Or whatever
return ret;
}
}
The last method lets you use type inference as well:
StuffDoer<int> doer = StuffDoer.Create(10);
This doesn't let you write new StuffDoer()
admittedly - but I think it's a cleaner solution. Creating a non-generic derived class just as a sort of "type alias" feels like an abuse of inheritance to me.
You can just setup a plain StuffDoer
class that inherits from StuffDoer<T>
:
public class StuffDoer : StuffDoer<string>
{
// ...
}
public class StuffDoer<T>
{
// ...
}
public class StuffDoer<T>
{
// do stuff
}
public class StuffDoer : StuffDoer<string>
{
// do stuff
}
精彩评论