【问题标题】:Merge extended class with the base class将扩展类与基类合并
【发布时间】:2016-09-28 07:49:38
【问题描述】:

我有两个类,一个叫做 MemberModel,一个叫做 CustomPrincipal。 CustomPrincipal 类继承了 MemberModel 类。

MemberModel 类如下所示:

namespace example.Models
{
    public class MemberModel
    {
        [Required]
        public string Username { get; set; }
        [Required]
        public string Password { get; set; }

        public bool Remember { get; set; }
    }
}

CustomPrincipal 类如下所示:

namespace example.Examples
{
    public class CustomPrincipal : MemberModel, IPrincipal
    {
        public CustomPrincipal(IIdentity identity)
        {
            this.Identity = identity;
        }

        public IIdentity Identity { get; private set; }

        public bool IsInRole(string role) { return false; }
    }
}

在下面的示例中,您会看到两个类 MemberModel 填充了用户名、密码和记忆,而 CustomPrincipal 类填充了 IIDentity 信息但不是用户名、密码和记忆。

JavaScriptSerializer serializer = new JavaScriptSerializer();
MemberModel memberModel = serializer.Deserialize<MemberModel>(authTicket.UserData);

IIdentity user = HttpContext.Current.User.Identity;
CustomPrincipal customPrincipal = new CustomPrincipal(user);

现在我希望将 MemberModel 的属性与 CustomPrincipal 的属性合并。

我尝试了多种方法,但都没有奏效。我尝试将 MemberModel 转换为 CustomPrincipal,但不幸的是这不起作用(见下文)。

customPrincipal = (CustomPrincipal) memberModel;
Unable to cast object of type 'example.Examples.Models.MemberModel' to type 'example.Examples.CustomPrincipal'.

我也试过Rob Harley的例子,它使用反射来合并两个对象,但这也没有用。

【问题讨论】:

  • 你期望最终达到的结果是什么?
  • @MongZhu 编辑问题:)
  • 恐怕最好的解决方案是在CustomPrincipal 中编写一个方法,将MemberModel 作为参数并手动设置这些属性或使构造函数接受MemberModel
  • 您可以在构造函数中添加参数,而不是方法。

标签: c# class inheritance merge base-class


【解决方案1】:

继承规则不允许您将基类 (MemberModel) 转换为子类 (CustomPrincipal)。您只能将子类转换回基类..

例如,

(DOG, CAT) =&gt; ANIMAL

我有一只狗和一只猫,我知道它们都是动物。所以,我可以把狗和猫当成动物。

CAT =&gt; ANIMAL =&gt; DOG

假设猫是动物,但你想把它变成狗,你做不到!为什么?因为你真的不知道它是不是狗。

你能做的最好的就是添加一个构造函数重载或一个从MemberModel返回CustomPrincipal的方法。

public CustomPrincipal(MemberModel model)
{
    this.Username = model.Username;
    ...
}

public static CustomPrincipal FromMember(MemberModel model)
{
    return new CustomPrincipal()
    {
        Username = model.Username,
        ...
    }
}

【讨论】:

  • 我的问题是如何自动做到这一点,如果我向 MemberModel 添加额外的属性,我不想将其也添加到 CustomPrincipal。
  • 我不知道任何可以为您自动执行操作的编程秘密。最短的方法是创建构造函数或转换器方法。
【解决方案2】:

最后我以正确的方式使用反射修复了它。

PropertyInfo[] props = typeof(MemberModel).GetProperties();
foreach (PropertyInfo prop in props)
{
    if (prop.Name != "Password")
        customPrincipal.GetType().GetProperty(prop.Name).SetValue(customPrincipal, serializeModel.GetType().GetProperty(prop.Name).GetValue(memberModel, null) as string);
}

首先我们从 MemberModel 中获取所有属性,然后我们遍历所有这些属性,并通过 MemberModel 的值设置 customPrincipal 的值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-31
    相关资源
    最近更新 更多