2009-09-04 4 views
0

one of my previous questions에서 (프로필 공급자를 사용하여) 사용자 프로필 개체에 데이터를 저장하기위한 양식 필드 개체를 포함하는 양식 클래스에 대해 설명했습니다.반성이나 대표자들과 함께 가야합니까 (C#)?

코드는 다음과 같습니다. 기본적으로 내가하고 싶은 것은 나중에 데이터를 저장하기 위해 상호 작용해야하는 Profile 객체의 필드를 양식 필드 객체에 매개 변수로 전달하는 것입니다.

당신은 다음 줄에 그것을 볼 수 있습니다 : 나는 반사에 대해 읽고 있었다

//LastNameFormLine is an control that was added to my form page. 
//The ProfileField parameter stores the field of the UserProfile object that is being manipulated by this control 
LastNameFormLine.ProfileField = "UserProfile.LastName"; 

는 UserProfileVisitor 클래스에서이 값을 절약 할 수 있도록,하지만 난 내가 C#에서 위임의 개념을 우연히 만났다 아직 완전히 이해할 수 있을지 모르겠다.

ProfileField를 UserProfile 클래스의 속성에 위임 할 수 있습니까? 아니면 그걸 잊어 버리고 반성해야합니까?

무엇을 제안하겠습니까?

public partial class UserProfileForm : CustomIntranetWebappUserControl 
{ 
    protected override void OnInit(EventArgs e) 
    { 
     //AutoEventWireup is set to false 
     Load += Page_Load; 
     CancelLinkButton.Click += CancelButtonClickEvent; 
     SaveLinkButton.Click += SaveButtonClickEvent; 
     base.OnInit(e); 
    } 

    private void SaveButtonClickEvent(object sender, EventArgs e) 
    { 
     VisitFormFields(); 
    } 

    private void VisitFormFields() 
    { 
     var userProfileVisitor = new UserProfileVisitor(); 

     foreach (var control in Controls) 
     { 
      if (control is FormFieldUserControl) 
      { 
       var formField = (FormFieldUserControl) control; 
       formField.Visit(userProfileVisitor); 
      } 
     } 
     userProfileVisitor.Save(); 
    } 

    protected void Page_Load(object sender, EventArgs e) 
    { 
     if (!IsPostBack) 
     { 
      BindText(); 
     } 
    } 

    private void BindText() 
    { 
     LastNameFormLine.LabelText = string.Format("{0}:", HomePage.Localize("Last Name")); 
     LastNameFormLine.InputValue = UserProfile.LastName; 
     LastNameFormLine.IsMandatoryField = true; 
     LastNameFormLine.IsMultilineField = false; 
     LastNameFormLine.ProfileField = "UserProfile.LastName"; 
     //... the rest of this method is exactly like the 4 lines above. 
    } 
} 

public abstract class FormFieldUserControl : CustomIntranetWebappUserControl 
{ 
    public string ProfileField { get; set; } 
    public abstract void Visit(UserProfileVisitor userProfileVisitor); 
} 


public partial class FormLineTextBox : FormFieldUserControl 
{ 
//... irrelevant code removed... 

    public override void Visit(UserProfileVisitor userProfileVisitor) 
    { 
     if (userProfileVisitor == null) 
     { 
      Log.Error("UserProfileVisitor not defined for the field: " + ProfileField); 
      return; 
     } 
     userProfileVisitor.Visit(this); 
    } 
} 

public class UserProfileVisitor 
{ 

    public void Visit(FormLineTextBox formLine) 
    { 
     // The value of formLine.ProfileField is null!!! 
     Log.Debug(string.Format("Saving form field type {1} with profile field [{0}] and value {2}", formLine.ProfileField, formLine.GetType().Name, formLine.InputValue)); 
    } 

    // ... removing irrelevant code... 

    public void Save() 
    { 
     Log.Debug("Triggering the save operation..."); 
    } 
} 
+1

링크를 짧게하지 마십시오. 대부분의 사람들은 링크가 클릭되기 전에 어디로 가는지보고 싶어합니다. – erelender

+0

왜 컨트롤을 직렬화 할 수 있습니까? 그건 말이되지 않습니다. – erikkallen

+0

@erelender : 게시물을 편집했습니다. 입력을 주셔서 감사합니다 – Pablo

답변

0

대리인은 속성을위한 것이 아닙니다. 그러나 리플렉션이 느리거나 코드 보안에 문제가있을 수 있으며 타입 안전하지 못해 런타임에 특성상 이름 지정 오류가 발생할 때 컴파일 타임에 문제가 생길 수 있습니다.

그렇다면 getter 및/또는 setter 메서드를 사용하고 해당 메서드에 대리자를 사용할 수 있습니다.

+0

getter/setter를 사용하지 않으려는 경우 속성 및 익명 메서드를 사용할 수 있습니다. –

+0

반영이 위임보다 빠릅니다. 이것을 읽으십시오 : http://www.palmmedia.de/Blog/2012/2/4/reflection-vs-compiled-expressions-vs-delegates-performance-comparision – Xxxo

+0

@Xxxo 주석과 downvote를 가져 주셔서 감사합니다. .NET 환경에서 "[Delegate] (https://msdn.microsoft.com/en-us/library/ms173171.aspx)"는 함수 포인터 개념의 관리되는 변형입니다. 언급 된 게시물은 잘못되었습니다. 예를 들어 "컴파일 된 표현식"의 경우는 실제로 대리인을 활용하는 경우입니다 (https://msdn.microsoft.com/en-us/library/system.linq.expressions.expression.lambda (v = vs.110)). aspx). 내 답변은 여전히 ​​정확하고 당신이 말하는 블로그 게시물은 "위임"케이스에 대한 정확한 용어를 사용하지 않습니다. 미안합니다 - 블로그 게시물 # 8, # 9 및 # 10도 참조하십시오. – Lucero

관련 문제