簡體   English   中英

在C#中,“ this”分配的示例是什么?

[英]What is an example of “this” assignment in C#?

有人在C#方法中有this分配的有用示例嗎? 面試時曾有人要求我這樣做,但我仍然有興趣回答自己。

當其他答案說您不能分配給“ this”時,其他答案是錯誤的。 是的,您不能使用類類型,但是可以使用結構類型:

public struct MyValueType
{
    public int Id;
    public void Swap(ref MyValueType other)
    {
        MyValueType temp = this;
        this = other;
        other = temp;
    }
}

在任何時候,結構都可以通過分配“ this”來改變自身,就像這樣。

使用this關鍵字可確保僅訪問當前類型范圍內的變量和方法。 當字段/屬性與局部變量或方法參數之間存在命名沖突時,可以使用此方法。

通常在構造函數中使用:

private readonly IProvider provider;
public MyClass(IProvider provider)
{
  this.provider = provider;
}

在此示例中,我們將參數提供程序分配給私有字段提供程序。

我知道這個問題早已得到解答,討論已經停止,但是在這種情況下,我在互聯網上的任何地方都沒有看到任何提及,並且認為在此處分享可能很有用。

我使用它來維護成員的不變性,同時仍支持序列化。 考慮這樣定義的struct

public struct SampleStruct : IXmlSerializable
{
    private readonly int _data;

    public int Data { get { return _data; } }

    public SampleStruct(int data)
    {
         _data = data;
    }

    #region IXmlSerializableMembers

    public XmlSchema GetSchema() { return null; }

    public void ReadXml(XmlReader reader)
    {
        this = new SampleStruct(int.Parse(reader.ReadString()));
    }

    public void WriteXml(XmlWriter writer
    {
        writer.WriteString(data.ToString());
    }

    #endregion
}

由於我們可以覆蓋this ,因此我們可以保持單個實例中_data的不變性。 反序列化新值時,可以確保獲得一個新實例,這有時是一個很好的保證! }

從語法角度來看,唯一正確的位置是將方法的第一個參數指定為foo(ftype this,...)時C#3.0中的擴展方法。 然后可以將此擴展名用於ftype的任何實例。 但是,這只是語法而不是真正的此ovveride操作。

如果你要求分配的東西這個 ,有相當多的例子。 我想到的是告訴控制對象他的父親是誰:

class frmMain
{
    void InitializeComponents()
    {
        btnOK = new Button();
        btnOK.Parent = this;
    }
}

您不能覆蓋“此”。 它指向當前的對象實例。

暫無
暫無

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

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