我有一个数据实体,其属性“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;
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; }
}
}
关于c# - 按名称将一种枚举类型转换为另一种枚举类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67016919/