C#:检查类型 T 是否为 bool

标签 c# compiler-errors

我不敢相信我不能用谷歌搜索这个。我不知道要谷歌什么。

public static T GetValue<T>(T defaultValue)
{
  if (T is bool) // <-- what is the correct syntax here?
    return (T)true; // <-- I don't think this works either
}

编辑:对不起,我没有提到,上面的功能只是为了显示我的问题。这不是一个真正的功能。谢谢大家的回答!

最佳答案

如果一个人必须使用相同的方法/签名并且必须使用T的类型(而且 这样做的原因,如果没有,请参阅 Albin 的回答):

public static T GetValue<T>(T defaultValue)
{
  // Need to use typeof to get a Type object for bool, just as with T
  if (typeof(T) == typeof(bool)) {
    // Need to say "get out of my way C#"
    // The first cast to object is required as true (bool) is
    // otherwise not castable to an unrestricted T.
    // This widen-restrict approach could result in a cast error,
    // but from the above check it is known that T is bool.
    return (T)(object)true;
  }
  // .. other stuff that .. does stuff.
}

但是,显式返回 true(这不是 bool 值的默认值)并完全忽略 defaultValue 似乎..可疑。但是 - It compiles! Ship it!

注意事项:

  • 对类型使用 == 对子类不能可靠地工作(但这没关系,因为 bool 是一个结构,所以子类型不是问题)。在这些情况下,请查看 IsAssignableFrom
  • typeof(T) 不一定是传入值的类型(对于引用类型可以是 null)。这与子类型一起,可能导致对值使用 is 的方法产生细微的变化。

关于C#:检查类型 T 是否为 bool,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13506794/

相关文章:

c++加解密源码

c++ - 奇怪的编译错误

c# - 为什么此处的Visual Studio无法解决List?

ios - 'GPUImageOutput<GPUImageInput>' 没有可见的@interface 声明选择器 'imageFromCurrentlyProcessedOutputWithOrientation:'

c# - 从顺序数据填充属性时创建类实例的最短方法

c# - tfs :"File is exclusively checked out by another user"- 哪个用户?

compiler-errors - MYSQL_INCLUDE_DIR 未找到

c# - StackExchange.Redis - 如何将项目添加到 Redis 集合

c# - DataContract/JsonSerializer '@' 附加到变量名称

c# - 添加 Controller 以编辑配置文件