Cos*_*ure 0 c# generics parameters
我需要为函数使用可选的泛型参数。这将是没有泛型参数的普通函数:
void MyFunction (string myText, int optionalParameter = 0)
{
//Do something
}
Run Code Online (Sandbox Code Playgroud)
我需要的是这个:
void MyFunction<T> (string myText, T optionalGenericParameter = default(T))
{
//Do something
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,初始化default(T)引发了以下错误“无法从用法推断出来。尝试明确指定类型参数。”
我经常遇到这个问题,我所做的是......过载
void MyFunction (string myText)
{
MyFunction (myText, 0);
// this works because C# will infer T as being int
}
void MyFunction<T> (string myText, T optionalGenericParameter)
{
//Do something
}
/* usage example:
MyFunction("foo");
MyFunction("bar", new Tuple<string, int>("yay", 113));
// C# will infer that T is Tuple<string, int> here.
*/
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9075 次 |
| 最近记录: |