【问题标题】:Converting one enum type to another by name按名称将一种枚举类型转换为另一种
【发布时间】:2021-04-09 07:36:34
【问题描述】:

我有一个数据实体,其属性“UserType”作为枚举返回,需要将其转换为另一个。

第一个枚举是(数字基于数据库中的值):

  public enum UserType
    {
        Primary = 100001,
        Secondary = 100002,
        Other = 100003
    }

这就是我想将其转换为:

    public enum UserType
    {
        Primary,
        Secondary,
        Other
    }

这是为了在这个类上设置 UserType:

public class UserData
    {
        public UserType UserType{ get; set; }
    }

可能是以下内容?

 MemberType = MemberType(entity.MemberType.ReadValue())

请问有人知道最好的方法吗?

【问题讨论】:

  • 首选项:创建一个接受OldUserType 并返回NewUserType 的映射。做不到这一点,也许Enum.Parse<NewUserType>(OldUserType.Primary.ToString());
  • 这能回答你的问题吗? convert an enum to another type of enum

标签: c#


【解决方案1】:

你可以使用Enum.Parse/Enum.TryParse:

A.UserType ut1 = A.UserType.Primary;
B.UserData data = new B.UserData();
data.UserType = Enum.TryParse(typeof(B.UserType), ut1.ToString(), true, out object ut2) ? (B.UserType)ut2 : B.UserType.Other;

AB 只是我用来区分这两个枚举的命名空间。为了模拟它,我使用了类:

public class A
{
    public enum UserType
    {
        Primary = 100001,
        Secondary = 100002,
        Other = 100003
    }
}

public class B
{
    public enum UserType
    {
        Primary,
        Secondary,
        Other
    }

    public class UserData
    {
        public UserType UserType { get; set; }
    }
}

【讨论】:

    【解决方案2】:

    如果你只需要一次或两次,老实说:我会手动编写:

    return value switch {
        Foo.A => Bar.A,
        Foo.B => Bar.B,
        Foo.C => Bar.C,
        _ => throw new ArgumentOutOfRangeException(nameof(value)),
    };
    

    在更一般的情况下:涉及ToString()Enum.Parse 的事情,例如:

    static TTo ConvertEnumByName<TFrom, TTo>(TFrom value, bool ignoreCase = false)
            where TFrom : struct
            where TTo : struct
            => Enum.Parse<TTo>(value.ToString(), ignoreCase);
    

    【讨论】:

      猜你喜欢
      • 2010-12-21
      • 1970-01-01
      • 1970-01-01
      • 2012-03-28
      • 1970-01-01
      • 2011-09-24
      • 1970-01-01
      • 1970-01-01
      • 2023-02-07
      相关资源
      最近更新 更多