2010-07-06 4 views
-1

변수 참조를 클래스로 전달한 다음 나중에 사용하고 싶습니다. 이 같은클래스 안팎으로 참조를 전달하는 방법

뭔가 :

// Create the comment Screen 
string newCommentText = ""; 
commentsScreen = new CommentEntry(this, ref newCommentText); 

commentScreen.ShowDialog(); 

... 

_dataLayer.SaveOffComment(newCommentText); 

그리고 주석 클래스 :

public partial class CommentEntry : Form 
{ 
    public CommentEntry(Control pControl, ref string commentResult) 
    { 
     InitializeComponent(); 
     control = pControl; 

     // ***** Need a way for this to store the reference not the value. ***** 
     _commentResult = commentResult; 
    } 


    private string _commentResult; 

    private void CommentEntry_Closing(object sender, CancelEventArgs e) 
    { 
     _commentResult = tbCommentText.Text.Trim(); 
    } 
} 

newCommentText 닫는 방법에 _commentResult에서 설정 한 값을 가질 수 있음을 어떻게든지 있는가?

참고 : 분명히 내 수업에 변수를 설정하고 ShowDialog 다음에 액세스하는 것이 쉬울 것입니다. 이 예제는 내 실제 문제의 근사치이며 ShowDialog가 완료된 후 클래스의 모든 변수에 액세스하는 것은 불가능합니다.

+2

을 더 간단한 옵션 또는 익명 대의원 (C# 2.0) (C#을 3.0) 대표와 람다 기능을 사용하는 것입니다 항상 클래스의 값을 랩핑합니다. –

+1

참조가 아닌 포인터를 원하는 것처럼 들립니다. –

+0

왜 불가능합니까? – Andy

답변

2

당신은 일반적으로 직접 C#에서 '참조 참조'를 저장할 수 없습니다,하지만 당신은 같은 것을 할 수있는 :

public interface ICommented 
{ 
    string Comment { get; set; } 
} 

public class MyClass : ICommented 
{ 
    public string Comment { get; set; } 
} 

public partial class CommentEntry : Form 
{ 
    public CommentEntry(Control pControl, ICommented commented) 
    { 
     InitializeComponent(); 
     control = pControl; 

     // ***** Need a way for this to store the reference not the value. ***** 
     _commented = commented; 
    } 


    private ICommented _commented; 

    private void CommentEntry_Closing(object sender, CancelEventArgs e) 
    { 
     _commented.Comment = tbCommentText.Text.Trim(); 
    } 
} 

는 이제 양식이 어떤 클래스의 코멘트를 편집 할 수 있습니다을 그 댓글을 달 수있는 방법을 알고 있다고 말했습니다.

+0

그 위대한 일했습니다! 아이디어를 가져 주셔서 감사합니다. – Vaccano

0

CommentEntry 클래스의 newComment 속성을 만듭니다.

+0

내 질문의 끝에 메모에서 말했듯이, 나는 ShowDialog 후에 클래스의 변수에 액세스 할 수 없다 – Vaccano

3

변수가 변경되지 않고 변수가 새 인스턴스를 가리 키도록 변경되므로 문자열과 함께 작동하지 않습니다.

두 가지 기본 옵션이 있습니다. 첫 번째는 나중에 결과가 필요할 때 액세스 할 수 있도록 결과에 대한 getter를 간단하게 가져 오는 것입니다. 또 다른 옵션은 소유자가 결과 값 전달을 호출 할 수있는 대리자 메서드에서 전달하도록하는 것입니다. 소유자는 CommentEntry가 닫힐 때 값을 수신합니다.

+0

대리인은 좋은 해결책이다 –

2

Dan Bryant가 지적했듯이, 직접 할 수는 없습니다. 하나의 옵션은 클래스에 레퍼런스를 래핑하는 것이지만, 많은 상용구 코드를 작성해야합니다.

string newCommentText = ""; 
// Using lambda that sets the value of (captured) variable 
commentsScreen = new CommentEntry(this, newValue => { 
    newCommentText = newValue }); 
commentScreen.ShowDialog(); 
_dataLayer.SaveOffComment(newCommentText); 

CommentEntry 형태의 수정 된 버전이 같을 것이다 : 당신은 할 수

public partial class CommentEntry : Form { 
    public CommentEntry(Control pControl, Action<string> reportResult) { 
    InitializeComponent(); 
    control = pControl; 
    // Store the delegate in a local field (no problem here) 
    _reportResult = reportResult;  
    } 

    private Action<string> _reportResult; 

    private void CommentEntry_Closing(object sender, CancelEventArgs e) { 
    // Invoke the delegate to notify the caller about the value 
    _reportResult(tbCommentText.Text.Trim()); 
    } 
} 
관련 문제