C# 按名称将一种枚举类型转换为另一种枚举类型

C# 按名称将一种枚举类型转换为另一种枚举类型,c#,C#,我有一个属性“UserType”作为枚举返回的数据实体,需要将其转换为另一个 第一个枚举是(数字基于数据库中的值): 这就是我想把它转换成的: public enum UserType { Primary, Secondary, Other } 这是为了设置此类的用户类型: public class UserData { public UserType UserType{ get; set; }

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

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

这就是我想把它转换成的:

    public enum UserType
    {
        Primary,
        Secondary,
        Other
    }
这是为了设置此类的用户类型:

public class UserData
    {
        public UserType UserType{ get; set; }
    }
也许是像下面这样的

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

有人知道这样做的最佳方法吗?

您可以使用
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;
A
B
正是我用来区分这两个枚举的名称空间。为了模拟它,我使用了以下类:

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; }
    }
}

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

返回值开关{
Foo.A=>Bar.A,
Foo.B=>Bar.B,
Foo.C=>Bar.C,
_=>抛出新ArgumentOutOfRangeException(nameof(value)),
};
在更一般的情况下:涉及
ToString()
Enum.Parse
的内容,例如:

静态TTo ConvertEnumByName(TFrom值,bool ignoreCase=false)
其中TFrom:struct
其中:struct
=>Enum.Parse(value.ToString(),ignoreCase);

首选项:创建一个接受
OldUserType
并返回
NewUserType
的映射。否则,可能是
Enum.Parse(OldUserType.Primary.ToString())?这是否回答了您的问题?
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; }
    }
}