c# - 将 T 限制为 int 值?

标签 c# generics compiler-errors

我该如何解决这个错误消息?

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

错误

Type of conditional expression cannot be determined because there is no implicit conversion between 'T' and 'int

最佳答案

如果您希望 T 是一个 int,接受一个 int 而不是 T。否则,如果 b == false,请考虑返回 default(T)。

返回 b ? v : 默认(T);

如果T是int,则返回0。如果是引用类型,则返回null。不断……

关于c# - 将 T 限制为 int 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2700419/

相关文章:

c# - 复杂 silverlight 游戏的最佳设计模式

c# - 减少 WMI 查询执行时间

C# WebClient,仅支持HTML3.2

java - 从不同对象获取值的通用方法,无需公共(public)父类(super class)型

xcode - 使用Xcode测试为Objective-C++代码库设置单元

c++ - 使用数据库结构的简单程序中未声明的标识符错误

c# - Selenium 在 Windows Server 上作为计划任务运行

generics - 具有多种类型的边界

java - java中如何决定使用哪个通配符?

c++ - 无法识别的命令行选项 '-std=c++11'