简体   繁体   中英

Inherit only limited properties in derived class in c#

In c#:

I have UserProfile class(model) which contains fields like: FName, LName, Email, Password

How can I create a class(model) which is derived from UserProfile class(model) and contains only selected properties.

For example, I want to create a Login class(model) from UserProfile class(model) and I only want to keep Email and Password properties.

I want to create ForgotPassword class(model) from UserProfile class(model) where I only want to keep Email property.

I don't know if this hierarchy suits your needs and specs but it seems you take the problem backwards.

You can write to respect the OOP principle of abstraction and inheritence (class names are not very relevant at first glance):

public class ForgotPassword
{
  public string Email;
}

public class Login : ForgotPassword
{
  public string Password;
}

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

I don't know if it is possible to do what you want to do...

In C#, I think not.

Example of using an interface combined with an abstract class:

// 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
}

I think using AutoMapper package suits your needs.

class parentA { public class AB { public void A_AB() { Console.WriteLine("Im AB from A"); } } public class AC { public void A_AC() { Console.WriteLine("Im AC from A"); } } } class B: parentA.AB {

}
class C : parentA.AC
{

}
class Program
{
    static void Main(string[] args)
    {
        C c = new C();
        B b = new B();
        c.A_AC();

        b.A_AB();

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM