簡體   English   中英

調用基本構造函數時如何使用“this”關鍵字

[英]How to use 'this' keyword when calling a base constructor

abstract class Foo 
{
    private readonly FooAttributeCollection attributes;

    public Foo(FooAttributeCollection attributes) 
    {
        this.attributes = attributes;
    }
}

class FooAttributeCollection 
{
    public FooAttributeCollection(Foo owner) 
    {
    }
}

class Bar : Foo 
{
    public Bar() : base(new FooAttributeCollection(this)) 
    {
    }
}

假設我必須編寫像上面這樣的代碼。 FooFooAttributeCollection類不能修改。

當我這樣寫Bar class 時,下面提到的錯誤:

'this' 關鍵字不能在此上下文中使用。

發生在線base(...)

有什么好主意來處理這件事嗎?

如果FooFooAttributeCollection不能修改,那么這段代碼似乎是一個糟糕的設計。 要實例化派生的 Foo class,您必須先實例化 FooAttributeCollection,而要實例化 FooAttributeCollection,您必須實例化相同的派生 Foo class。 沒有“作弊”就無法解決無休止的循環依賴

也許這個問題可以通過反射來解決(如 Uwe Keim 所說),或者通過使用真正的代理/動態代理來創建 DerivedClass 的代理。

你不能寫:

public Bar() : base(new FooAttributeCollection(this)) 

this ,當前的 object,必須放在方法的實現中,而不是放在方法簽名中:這里您無法訪問 object 的當前實例。

你不能在每個方法聲明中做這樣的事情,因為你不在實現 scope 中,你在類型 def scope 中,即在 class 的“接口”中,在它的定義中。

使用basethis關鍵字調用 base 或 side 構造函數是一種特殊的語言構造,用於傳遞不是 class 本身的實例的參數。

您可以使用@Tohm 解決方案來解決您的目標。

為什么不影響抽象 class 中的屬性? 如果你想要在 FooAttributeCollection 中,你可以在 Bar class 中轉換所有者。

abstract class Foo 
{
    private readonly FooAttributeCollection attributes;

    public Foo(FooAttributeCollection attributes=null) 
    {
        if(attributes = null) {attributes = new FooAttributeCollection(this);}
        this.attributes = attributes;
    }
}

class FooAttributeCollection 
{
    public FooAttributeCollection(Foo owner) 
    {
        var ownerInBar = owner as Bar;

    }
}

class Bar : Foo 
{
    public Bar() : base() 
    {
    }
}

需要先構造 class 才能訪問this關鍵字。

你可以試試下面的。

class Bar : Foo
    {
        private readonly FooAttributeCollection attributes;
        public Bar() : base(null)
        {
            var attributes = new FooAttributeCollection(this);
        }
    }

試試這個方法:

public class Bar : Foo
    {
        public Bar(FooAttributeCollection attributes) : base(attributes)
        {
        }
    }

其他示例:

public class BaseClass
    {
        int num;
        public BaseClass(int i)
        {
            num = i;
            Console.WriteLine("in BaseClass(int i)");
        }
    }
public class DerivedClass : BaseClass
    {         
        // This constructor will call BaseClass.BaseClass(int i)
        public DerivedClass(int i) : base(i)
        {
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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