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

标签 c#

我有一个数据实体,其属性“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())

有人知道最好的方法吗?

最佳答案

您可以使用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; }
    }
}

关于c# - 按名称将一种枚举类型转换为另一种枚举类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67016919/

相关文章:

c# - 多线程时 i 的错误值?

c# - 如何在C#wpf中获取登录用户的文档路径

c# - 多个并发操作的 UI 更新

c# - 为什么 Parallel.For 会执行 WinForms 消息泵,如何防止?

c# - 使用 C# 的 SerialPort 类将命令传递到 Com 端口

c# - Visual Studio 2015 (Windows 10) 中的 .NET Native 编译失败

c# - 从 Angular 2 调用 WCF 服务

c# - 非托管对象的 GC.AddMemoryPressure

c# - 使用 linq 从 List<Postavke>() 查找属性值

c# - 如何对抽象类进行单元测试