【问题标题】:Inherit only limited properties in derived class in c#在 C# 中仅继承派生类中的有限属性
【发布时间】:2020-01-29 15:25:33
【问题描述】:

在 C# 中:

我有 UserProfile 类(模型),其中包含以下字段:FName、LName、Email、Password

如何创建一个派生自 UserProfile 类(模型)且仅包含选定属性的类(模型)。

例如,我想从 UserProfile 类(模型)创建一个登录类(模型),我只想保留电子邮件和密码属性。

我想从我只想保留 Email 属性的 UserProfile 类(模型)创建 ForgotPassword 类(模型)。

【问题讨论】:

标签: c# inheritance abstract-class derived-class solid-principles


【解决方案1】:

我不知道这种层次结构是否适合您的需求和规格,但您似乎把问题倒退了。

你可以写尊重抽象和继承的OOP原则(类名乍一看不是很相关):

public class ForgotPassword
{
  public string Email;
}

public class Login : ForgotPassword
{
  public string Password;
}

public class UserProfile : Login
{
  public string FName;
  public string LName;
}

不知道有没有可能做你想做的事……

在 C# 中,我认为不是。

【讨论】:

    【解决方案2】:

    使用接口结合抽象类的例子:

    // Different interfaces
    interface IUserData
    {
        string Email;
        string Password;
    }
    
    interface IUserNameData
    {
        public abstract string FName;
        public abstract string LName;
    }
    
    // Abstract class
    abstract class UserProfile : IUserData
    {
        public abstract string Email;
        public abstract string Password;
    }
    
    
    // Inherited classs
    class LoginData : UserProfile
    {
        // Implements IUserData
    }
    
    class UserData : UserProfile, IUserNameData
    {
        // Implements IUserData and IUserNameData
    }
    

    【讨论】:

      【解决方案3】:

      我认为使用 AutoMapper 包适合您的需求。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-10-25
        • 2022-12-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多