[英]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
. 现在,从
MyUser
类,我希望能够访问dir
肯定可以期望的MyDirectory
实例。 How does a C# programmer achieve this in style? C#程序员如何实现这种风格? Overwrite
_DIR
in MyUser
with a private property that contains the uncasted MyDirectory, using a cast everywhere, anything else entirely? 使用包含未广播的MyDirectory的私有属性覆盖
MyUser
_DIR
,并在MyUser
使用强制转换,还有其他功能吗?
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: 但是我要做的是在
BaseUser
抽象类中使用泛型来指定所使用的目录类型:
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
. 这样,您可以访问类型为
MyDirectory
而不是BaseDirectory
的_dir-Variable。 If you need to have multiple instances of MyUser
with different Directories, you could also make the MyUser
class generic. 如果需要具有不同目录的
MyUser
多个实例,则还可以使MyUser
类通用。
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. 您可以在
MyUser
类中保存类型转换_DIR
字段。 Through the constructor it is ensured, to have a instane of MyDirectory
there: 通过构造函数,可以确保在那里拥有
MyDirectory
的实例:
(_DIR as MyDirectory).SomeMethod()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.