无论如何默认一个泛型参数到某种类型? [英] Anyway to default a generic parameter to a certain type?
问题描述
有没有办法为通用的参数T提供一个默认类型,如下所示:
class Something< T = string>
{
}
我知道没有太多有力的理由,但我想提示代码客户端的类型,他应该优先使用。
另一件事,我可以限制泛型类型为我刚才看到你不能,但是我仍然想知道为什么。任何人都有线索? ValueType
?
谢谢! 好的,我假设你有这个类:
class Something< T>
{
}
现在,您可能需要另一个班级:
class Something:Something< string>
{
//没有更多的代码需要在这里!
}
这是唯一的最好的方法。
所以如果使用 Something
,他实际上会使用 Something< string>
。
Is there a way to provide a default type for a parameter T of a generic, something like:
class Something<T = string>
{
}
I know there aren't many strong reasons for this, but I would like to hint the code client which type he should be preferably using.
Another thing, can I restrict the generic type to a I've just seen that you can't, but still, I'd like to know why. Anyone has a clue?ValueType
?
Thanks!
Ok, I suppose you have the class:
class Something<T>
{
}
Now, you might want another class:
class Something : Something<string>
{
// NO MORE CODE NEEDED HERE!
}
This is the only and the best way.
So if one uses Something
he will actually use Something<string>
.
这篇关于无论如何默认一个泛型参数到某种类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!