[英]C# Specify that a derived field is derived from its original class
假设我有一个B
, B:A
和D:C
的类A
, B
, C
和D
A
有一个带有C
对象的字段,该字段继承给B
并且在A
中的不同方法中A
。 我知道要在B
指定该对象,它不仅是C
对象,而且是D
对象,但仍然利用A
中对C
对象进行操作的方法。
public class A
{
public C Obj { get; set; }
public void DoStuff()
{
// Do stuff with Obj (C)
}
}
public class B : A
{
public D Obj { get; set; } // This should also be the C Obj in A
public void DoMoreStuff()
{
// Do stuff with Obj (D)
}
}
public class C
{
// ...
}
public class D : C
{
// ...
}
具体来说,我需要使用它来实现二叉树。 二进制搜索树(BST)的根是BST节点,并提供了利用它的不同方法。 红黑树也是BST,但根是RBT节点,它也是BST节点,但还具有颜色属性。
您可以使用通用基类来执行所需的操作。 尝试从此开始:
public abstract class A<T> where T : C
{
public T Obj { get; set; }
public void DoStuff()
{
Console.WriteLine(typeof(T).FullName);
Console.WriteLine(this.Obj.GetType().FullName);
}
}
现在,您可以轻松定义A
和B
:
public class A : A<C>
{
}
public class B : A<D>
{
public void DoMoreStuff()
{
this.DoStuff();
Console.WriteLine(this.Obj.GetType().FullName);
}
}
如果我运行此代码:
var a = new A() { Obj = new C() };
var b = new B() { Obj = new D() };
a.DoStuff();
Console.WriteLine("...");
b.DoMoreStuff();
我得到:
C C ... D D D
使用泛型非常容易:
public class A<T> where T : C
{
public T Obj { get; set; }
public void DoStuff()
{
// Do stuff with Obj (C)
}
}
public class B<T> : A<T> where T : D // this condition is valid since D inherits C
{
public T Obj { get; set; }
public void DoMoreStuff()
{
// Do stuff with Obj (D)
}
}
public class C
{
// ...
}
public class D : C
{
// ...
}
您可以添加一些泛型来访问所需的属性。 我觉得这是一项家庭作业,所以我只提供一些基础知识。 查看代码中的注释以获取更多详细信息
public abstract class BaseTree<TNode>
where TNode : BaseNode // TNode must be at least (base class) a BaseNode
{
// Can be a collection as well, depending on your needs
public TNode Node { get; set; }
public void DoStuff()
{
// Node is a BaseNode
}
}
// Any node in this tree is a RedBlackNode
public class RedBlackTree : BaseTree<RedBlackNode>
{
public void DoMoreStuff()
{
// Node is a RedBlackNode
}
}
public abstract class BaseNode
{
}
public class RedBlackNode : BaseNode
{
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.