将T限制为int值?

3 c# generics compiler-errors

我怎样才能解决这个错误消息?

static public class Blah
{
    public static T val<T>(this bool b, T v) { return b == true? v:0; }
}
Run Code Online (Sandbox Code Playgroud)

错误

Type of conditional expression cannot be determined because there is no implicit conversion between 'T' and 'int
Run Code Online (Sandbox Code Playgroud)

Ant*_*ram 14

如果你想让T成为一个int,接受一个int而不是一个T.否则,如果b == false,则考虑返回default(T).

return b ? v : default(T);

如果T是一个int,它将返回0.如果它是一个引用类型,它将为null.并且......


Mar*_*off 5

如果你只想要一个int,你为什么要尝试使用泛型?

// No need to compare b to true...
public static int val(this bool b, int v) { return b ? v : 0; }
Run Code Online (Sandbox Code Playgroud)

否则,default(T)像其他人提到的那样使用.

public static T val<T>(this bool b, T v) { return b ? v : default(T); }
Run Code Online (Sandbox Code Playgroud)

default(T)对于ints和其他数值,false对于bools,null对于对象,默认为0 ...


Cam*_*and 5

如果要返回T的"默认"值:

public static T val<T>(this bool b, T v) { return b == true? v : default(T); }
Run Code Online (Sandbox Code Playgroud)

默认值表
默认关键字在通用代码中