简体   繁体   中英

Implementing an abstract class hierarchy -

I make an abstract class hierarchy, for example:

abstract public class BaseDirectory {
}

abstract public class BaseUser() {
    protected readonly BaseDirectory _DIR
    BaseUser(BaseDirectory dir) {
        _DIR = dir;
    }
}

And then I implement that abstract hierarchy:

class MyDirectory : BaseDirectory {
    internal void SomeMethod() {
    }
}

class MyUser : BaseUser {
    MyUser(MyDirectory dir) : base(dir)
    {
    }
    internal void SomeMethod() {
        _DIR.SomeMethod(); // <- how to do this?
    }
}

Now, from the MyUser class, I want to be able to access the MyDirectory instance that I can certainly expect in dir . How does a C# programmer achieve this in style? Overwrite _DIR in MyUser with a private property that contains the uncasted MyDirectory, using a cast everywhere, anything else entirely?

It probably depends on the use case. But what I would do is use generics in the BaseUser abstract class to specify the directory type used:

Image something like this:

public abstract class BaseDirectory
{

}

public abstract class BaseUser<TDirectory> where TDirectory : BaseDirectory
{
    protected readonly TDirectory _dir;
    protected BaseUser(TDirectory dir)
    {
        _dir = dir;
    }
}

public class MyDirectory : BaseDirectory
{
    public void SpecificMethod() { }
}

public class MyUser : BaseUser<MyDirectory>
{
    public MyUser(MyDirectory dir) : base(dir)
    {

    }

    internal void SomeMethod()
    {
        // call specific method on type MyDirectory
        _dir.SpecificMethod();
    }
}

That way you can acces the _dir-Variable which is of type MyDirectory and not BaseDirectory . If you need to have multiple instances of MyUser with different Directories, you could also make the MyUser class generic.

I may be totally wrong, and this is total garbage, but thats at least how I would do it : )

You can savely typecast the _DIR field in the MyUser class. Through the constructor it is ensured, to have a instane of MyDirectory there:

(_DIR as MyDirectory).SomeMethod()

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