【问题标题】:Cannot define T in C# [duplicate]无法在 C# 中定义 T [重复]
【发布时间】:2016-01-15 18:38:26
【问题描述】:

知道如何在这段代码中定义 T 吗?

 public static T ToEnum<T>(this string value, T defaultValue)
        {
            if (string.IsNullOrEmpty(value))
            {
                return defaultValue;
            }

            T result;
            return Enum.TryParse<T>(value, true, out result) ? result : defaultValue;
        }

严重性代码描述项目文件行错误 CS0453 类型“T” 必须是不可为空的值类型才能将其用作参数 泛型类型或方法中的 'TEnum' Enum.TryParse(string, bool, out TEnum)'

【问题讨论】:

  • @PetSerAl 请写出整个代码,就像答案一样。谢谢!
  • 请阅读How to Ask。如果您可以定义“this”,则可以搜索它。你想要一个“枚举的通用类型约束”吗?

标签: c# .net


【解决方案1】:

尝试使用constraint 来获得struct 的值类型,例如:

public static T ToEnum<T>(this string value, T defaultValue)
      where T : struct 
{
    if (string.IsNullOrEmpty(value))
    {
        return defaultValue;
    }

    T result;
    return Enum.TryParse<T>(value, true, out result) ? result : defaultValue;
}

我没有测试过。

【讨论】:

  • 比我快一秒!
  • 它给出了错误Severity Code Description Project File Line Error CS0451 The 'new()' constraint cannot be used with the 'struct' constraint
  • 尝试使用“枚举”作为约束!
  • 删除, new() OP,枚举不能是“新”
  • where T : Enum 在 C# 中不是有效的模板约束。
猜你喜欢
  • 2021-08-23
  • 1970-01-01
  • 1970-01-01
  • 2012-10-13
  • 2019-10-11
  • 2020-09-14
  • 2016-08-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多