相关疑难解决方法(0)

创建将T限制为枚举的通用方法

我正在构建一个扩展Enum.Parse概念的函数

  • 允许在未找到枚举值的情况下解析默认值
  • 不区分大小写

所以我写了以下内容:

public static T GetEnumFromString<T>(string value, T defaultValue) where T : Enum
{
    if (string.IsNullOrEmpty(value)) return defaultValue;
    foreach (T item in Enum.GetValues(typeof(T)))
    {
        if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;
    }
    return defaultValue;
}
Run Code Online (Sandbox Code Playgroud)

我得到一个Error Constraint不能是特殊类System.Enum.

很公平,但是有一个解决方法允许Generic Enum,或者我将不得不模仿该Parse函数并将类型作为属性传递,这会迫使您的代码出现丑陋的拳击要求.

编辑以下所有建议都非常感谢,谢谢.

已经解决了(我已离开循环以保持不区分大小写 - 我在解析XML时使用它)

public static class EnumUtils
{
    public static T ParseEnum<T>(string value, T defaultValue) where T : struct, IConvertible
    {
        if (!typeof(T).IsEnum) throw new ArgumentException("T must be an enumerated type");
        if (string.IsNullOrEmpty(value)) return …
Run Code Online (Sandbox Code Playgroud)

c# generics enums generic-constraints

1122
推荐指数
12
解决办法
33万
查看次数

将枚举值的通用列表组合为单个值的 C# 方法

我想传递一个IEnumerable<T>枚举值(枚举具有 Flags 属性)并返回聚合值。下面的方法有效,但前提是枚举使用默认Int32类型。如果它使用byteInt64它将不起作用。

public static T ToCombined<T>(this IEnumerable<T> list) where T : struct
{
    if (!typeof(T).IsEnum)
        throw new ArgumentException("The generic type parameter must be an Enum.");
    var values = list.Select(v => Convert.ToInt32(v));
    var result = values.Aggregate((current, next) => current | next);
    return (T)(object)result;
}
Run Code Online (Sandbox Code Playgroud)

我知道我可以获得基础类型:

Type enumType = typeof(T);
Type underlyingType = Enum.GetUnderlyingType(enumType);
Run Code Online (Sandbox Code Playgroud)

但我不知道如何在方法中使用它。我如何制作扩展方法,以便它可以处理enums具有 flags 属性的任何列表?

更好,但可能是非常大的 UInts 的问题

public static T ToCombined<T>(this IEnumerable<T> list) where T : struct
{ …
Run Code Online (Sandbox Code Playgroud)

c#

5
推荐指数
2
解决办法
1046
查看次数

标签 统计

c# ×2

enums ×1

generic-constraints ×1

generics ×1