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

前端之家收集整理的这篇文章主要介绍了如何在C#中传递当前实例的引用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
例如像(参考这个)不起作用的东西……例如这失败了:
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

解决方法

这已经是一个参考.代码就像
DoSomethingWith(this);

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

猜你在找的C#相关文章