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

时间:2012-11-22 06:10:58

标签: 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
}
编辑:对不起,我没有提及,上面的功能只是为了表明我的问题。它不是一个真正的功能。谢谢大家的答案!

3 个答案:

答案 0 :(得分:12)

如果一个必须使用相同的方法/签名,并且必须使用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(这不是布尔值的默认值)并完全忽略defaultValue似乎是......可疑。但是 - It compiles! Ship it!

注意:

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

答案 1 :(得分:8)

不检查类型,检查变量

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

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

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

public static bool GetValue(bool defaultValue)
{
    return true;
}

答案 2 :(得分:3)

也许您正在寻找default(T),它会返回提供类型的默认值。 bool的默认值为false