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

Axi*_*ili 7 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
}
Run Code Online (Sandbox Code Playgroud)

编辑:对不起我没提,上面的功能只是为了表明我的问题.这不是一个真正的功能.谢谢大家的答案!

小智 17

如果必须使用相同的方法/签名并且必须使用类型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.
}
Run Code Online (Sandbox Code Playgroud)

但是,显式返回true(这不是布尔值的默认值)并defaultValue完全忽略似乎......可疑.但是 - 它编译!装运它!

笔记:

  • 对于子类的使用==无法可靠地用于子类(但它没关系,因为它bool是一种结构,因此子类型不是问题).在那些情况下,看看IsAssignableFrom.
  • typeof(T)不一定是传入的值的类型(可以是null引用类型).这与子类型一起,可以导致对is值使用的方法的细微变化.


Alb*_*nbo 8

不检查类型,检查变量

public static T GetValue<T>(T defaultValue)
{
  if (defaultValue is bool) // <-- what is the correct syntax here?
    return (T)true;
}
Run Code Online (Sandbox Code Playgroud)

但是,作为一个方面,当您进行类型检查并对通用类型中的不同类型进行不同处理时,您通常会做错事.

为什么不为具有特殊处理的类型创建重载?

public static bool GetValue(bool defaultValue)
{
    return true;
}
Run Code Online (Sandbox Code Playgroud)