如何在C#中传递当前实例的引用

Sam*_*hid 6 c# reference

例如像(ref this)这样的东西不起作用......例如,这失败了:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CopyOfThis
{
    class Program
    {
        static void Main(string[] args)
        {
            View objView = new View();
            objView.Boo();
            objView.ShowMsg("The objView.StrVal is " + objView.StrVal);
            Console.Read();
        }
    } //eof Program


    class View
    {
        private string strVal;
        public string StrVal
        {
            get { return strVal; }
            set { strVal = value; } 

        }
        public void Boo()
        {
            Controller objController = new Controller(ref this);
        }

        public void ShowMsg ( string msg ) 
        {
            Console.WriteLine(msg); 
        }


    } //eof class 

    class Controller
    {
        View View { get; set; } 
        public Controller(View objView)
        {
            this.View = objView;
            this.LoadData();
        }

        public void LoadData()
        {
            this.View.StrVal = "newData";
            this.View.ShowMsg("the loaded data is" + this.View.StrVal); 
        }
    } //eof class 

    class Model
    { 

    } //eof class 
} //eof namespace 
Run Code Online (Sandbox Code Playgroud)

Pet*_*old 14

this已经是一个参考.代码就像

DoSomethingWith(this);
Run Code Online (Sandbox Code Playgroud)

将引用传递给当前对象的方法DoSomethingWith.


And*_*tan 5

编辑:鉴于您编辑的代码示例,您不需要通过ref this,因为正如接受的答案所述 - 这已经是一个参考。

你不能通过this引用传递引用,因为它是常量;通过 ref 传递它将允许它被更改 - 就 C# 而言,这是无意义的。

你能得到的最接近的结果是:

var this2 = this;
foo(ref this2);
Run Code Online (Sandbox Code Playgroud)