8

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

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
}

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

4

3 回答 3

22

如果必须使用相同的方法/签名并且必须使用的类型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完全忽略,否则似乎.. 可疑。但是 -它编译!装运它!

笔记:

  • ==Types的使用对于子类不能可靠地工作(但没关系,因为它bool是一个结构,所以子类型不是问题)。在这些情况下,请查看IsAssignableFrom.
  • typeof(T)不一定是传入的值的类型(可能是null引用类型)。这与子类型一起,可能导致is在值上使用的方法发生细微的变化。
于 2012-11-22T06:27:29.943 回答
13

不要检查类型,检查变量

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;
}
于 2012-11-22T06:13:15.570 回答
3

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

于 2012-11-22T06:22:48.407 回答