1

我有一个class Claim和一个Enum Role

我经常需要转换ClaimRole或相反。

通常我也会转换List<Claim>List<Role>或相反。

在这种情况下,角色是以下枚举:

public enum Role {
  Leader = 1,
  Editor = 2
} // Role

注意:为简单起见,仅包括 2 个项目。

那么一个 Claim 是一个具有两个属性的类:

public class Claim {
  public String Type { get; set; }
  public String Value { get; set; }
}
  1. 转换RoleClaim

    Claim.Type = "Role" and Claim.Value={Role Text} (Example: Leader)

  2. 转换RoleClaim

仅适用于ClaimsType 为Role.

在这些情况下,如果 (1)

我不确定类型转换器是否是最佳解决方案。

但我想以某种方式使这些转换尽可能简单。

一些可重用的东西,因为我经常需要进行这种转换。

也许是一个扩展?帮手?类型转换器?

4

3 回答 3

6

TypeConverter 不是您想要的,它的实现往往更加密集,更加迟钝,并允许您似乎不需要的设计时功能。如果您的目标是允许使用这些对象的人在需要最少代码的情况下在两者之间移动,则可以定义隐式转换(或显式转换,如果您想强制转换语法)。

public class Claim
{
    public String Type { get; set; }
    public String Value { get; set; }

    public static implicit operator Role(Claim claim)
    {
        return (Role)Enum.Parse(typeof(Role), claim.Value);
    }
    public static implicit operator Claim(Role role)
    {
        return new Claim() { Type = "Role", Value = role.ToString() };
    }
}

这样做将允许以下代码工作,因为它将利用您定义的转换。

Claim claim = Role.Leader;
Role role = claim;  

更新

您在评论中说您不能触摸 Claim 类。那么,最简​​单的方法可能是扩展方法。

static class ClaimExtensions
{
    public static Role ToRole(this Claim claim)
    {
        return (Role)Enum.Parse(typeof(Role), claim.Value);
    }
    public static Claim ToClaim(this Role role)
    {
        return new Claim() { Type = "Role", Value = role.ToString() };
    }
}

这意味着方法调用,但开发人员使用和理解起来相当简单。

Claim claim = Role.Leader.ToClaim();
Role role = claim.ToRole();
于 2013-05-03T21:35:47.240 回答
0

If you want to "fetch" or create one based on the value of another, you can to two things:

1 - To go from an enum to a class, I would use a Factory Method. Pass in a enum and return a class of the appropriate type.

2 - I would change the claim "Type" property to an enum of type Role, so that you can instantly retrieve the enum value associated with the caim.

If that cannot work since "Type" can possibly hold values not in the Role enum, then I would add a property possibly nullable of type Role.

于 2013-05-03T21:37:02.847 回答
0

我如何为此创建和使用类型转换器?

您刚刚阅读了如何:实现类型转换器

于 2013-05-03T21:14:06.543 回答