2010-01-12 4 views
6

예 : 작동하지 않는 것과 같은 (ref this) ... 예 : 실패 :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 
+4

좀 더 자세한 정보를 제공해 주시겠습니까? 응용 프로그램에 필요한 예제가 있으면 누군가가 대답하기가 더 쉬워 질 수 있습니다. –

답변

14

this은 이미 참조 대상입니다.

과 같은 코드는 현재 개체에 대한 참조를 DoSomethingWith 메서드에 전달합니다.

+0

I * think * OP가 참조 사본을 전달하고자 할 수 있습니다. 그러므로 quesiton의 "(ref this)"비트를 참조하십시오. 잘못은 아니지만 실제로는 명확하지 않습니다. –

+0

물론 메서드가 동일한 개체에 있으면 어쨌든 그것을 전달할 필요가 없습니다. 메서드에서이 메서드를 사용하십시오. –

+0

Jupp. OP가 우리에게 더 많은 배경을 제공 할 때 그에 따라 개정 할 것입니다. –

0

ref으로 전달 된 변수는 초기화해야합니다.

4

편집 : 수정 된 코드 예제를 사용하면 허용 된 답변 상태이므로 ref this을 전달할 필요가 없습니다. 이미 참조 된 상태입니다.

this 참조 정보는 상수이기 때문에 참조 할 수 없습니다. ref로 전달하면 변경 될 수 있습니다. C#에 관한 한 말도 안됩니다.

var this2 = this; 
foo(ref this2); 
0

을이 같은 방법이있는 경우 :

void Foo(ref Bar value) { 
    // bla bla 
} 

당신은이 같은 임시 변수를 만들어 줄 객체에서 호출 할 수

당신이 얻을 수있는 가장 가까운하는 것입니다

var temp = this; 
foo.Foo(ref temp); 
관련 문제