簡體   English   中英

C#指定派生字段是從其原始類派生的

[英]C# Specify that a derived field is derived from its original class

假設我有一個BB:AD:C的類ABCD

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);
    }
}

現在,您可以輕松定義AB

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM