Options for developing classes using secure downcasting

After struggling with downcasting (see [my original post] ) and using [deep copies] , I found [this article of the same name] , where in C ++ it was suggested how to deal with this problem. With great excitement, I implemented it in C # as follows:

public partial class User
{
virtual public Employer GetEmployer() { return null; }
...
}

public partial class Employer
{
public override Employer GetEmployer() { return this; }
...
}

which I then used as follows:

User u = GetUser();
Employer e = u.GetEmployer();

However (I suppose not surprisingly), an override is never called and returns null.


, , - , , : , , . , () .

-, -, , User, . ( ), , Employer, User.

?

0
3

. -, . . , - is a. , :

public class User { }

public class Employee : User { }

Employeee is User, User is Employee. , User Employee. User Employee ( , , ).

, - - .

public class User 
{
    public virtual EmployeeData { get; set; }
}

public class EmployeeData { }

is a has a. EmployeeData , 1 - 0..1 ( ). 1 - 1 ComplexType, , User EmployeeData .

+1

, Employer .

:

public partial class Employer : User
{
    // ...
}

. , . , , as :

var user = GetUser();
var employer = user as Employer;

// if the cast failed, employer will be null
if(employer != null)
{
    // Work with employer
}
0

:

.

Prototype Pattern:

[] , .

- :

// State pattern: public "wrapper"
public class User {
    UserState state = UserState.CreateUser();

    public void SetIsEmployer ()
    {
        // Use UserState.IsEmployer() method to transition to the
        // Employer state
        state = state.IsEmployer ();
    }

    public User Employer {
        get {return state.Employer.User;}
    }
}

// State pattern: User state
internal class UserState {
    // protected so that only CreateUser() can create instances.
    protected UserState ()
    {
    }

    public User User {
        get {/* TODO */}
    }

    public virtual UserState Employer {
        get {return null;}
    }

    // Creates a default prototype instance
    public static UserState CreateUser ()
    {
         return new UserState ();
    }

    // Prototype-ish method; creates an EmployerState instance
    public virtual UserState IsEmployer ()
    {
        return new EmployerState (/* data to copy...*/);
    }
}

// State pattern: Employer state
class EmployerState : UserState {
    internal EmployeeState ()
    {
    }

    public override UserState Employer {
        get {return this;}
    }
}

User " ", ( ) - UserState. User.state User. .

0

All Articles