2012-07-05 3 views
0

실제로 정확히 어떻게 그 일이 정확하게 호출되는지 말할 수는 없지만 한 가지 방법으로 변수/속성/필드를 지정할 수있는 것이 필요합니다.람다 식/델리게이트 할당 변수

txtBox.Text = SectionKeyName1; //this is string property of control or of any other type 
if (!string.IsNullOrEmpty(SectionKeyName1)) 
{ 
    string translation = Translator.Translate(SectionKeyName1); 
    if (!string.IsNullOrEmpty(translation)) 
    { 
     txtBox.Text = translation; 
    } 
} 

stringField = SectionKeyName2; //this is class scope string field 
if (!string.IsNullOrEmpty(SectionKeyName2)) 
{ 
    string translation = Translator.Translate(SectionKeyName2); 
    if (!string.IsNullOrEmpty(translation)) 
    { 
     stringField = translation; 
    } 
} 

stringVariable = SectionKeyName3; //this is method scope string variable 
if (!string.IsNullOrEmpty(SectionKeyName3)) 
{ 
    string translation = Translator.Translate(SectionKeyName3); 
    if (!string.IsNullOrEmpty(translation)) 
    { 
     stringVariable = translation; 
    } 
} 

내가 볼 수있는 바와 같이,이 코드는 하나의 방법으로 리팩토링 할 수 있습니다 설정하고 SectionKeyName 할 수있는 "개체를"수신 : 나는 ... 설명하기 위해 나는 다음과 같은 코드가 을 다할 것입니다. 그래서이 될 수 같은 :

public void Translate(ref target, string SectionKeyName) 
{ 
    target = SectionKeyName; 
    if (!string.IsNullOrEmpty(SectionKeyName)) 
    { 
     string translation = Translator.Translate(SectionKeyName); 
     if (!string.IsNullOrEmpty(translation)) 
     { 
      target = translation; 
     } 
    } 
} 

하지만 : 나는 texBox.Text을 할당 할 때 특성이하는 ByRef .... I found topic on SO where is solution for properties 전달 될 수 없기 때문에 나는 경우에이 방법을 사용할 수 없습니다 것입니다, 하지만 ...

내 모든 경우를 처리하는 하나의 방법을 쓸 수있는 방법을 찾아 도와주세요 ....

//This method will work to by varFieldProp = Translate(SectionKeyName, SectionKeyName), but would like to see how to do it with Lambda Expressions. 
public string Translate(string SectionKeyName, string DefaultValue) 
{ 
    string res = DefaultValue; //this is string property of control or of any other type 
    if (!string.IsNullOrEmpty(SectionKeyName)) 
    { 
     string translation = Translator.Translate(SectionKeyName); 
     if (!string.IsNullOrEmpty(translation)) 
     { 
      res = translation; 
     } 
    } 

    return res; 
} 

감사를이 속성을 해결하고 난 필드/변수와 함께 붙어 너 !!!

+1

"람다 표현식으로 어떻게 수행하는지보고 싶습니다."- 개선되지는 않을 것입니다. 마지막 함수 변형을 사용하면됩니다. 그것은 간단하고 요점입니다. –

답변

3

난 당신이 뭔가 싶은 생각 :

public void Translate(Action<string> assignToTarget, string SectionKeyName) 
     { 
      assignToTarget(SectionKeyName); 
      if (!string.IsNullOrEmpty(SectionKeyName)) 
      { 
       string translation = Translator.Translate(SectionKeyName); 
       if (!string.IsNullOrEmpty(translation)) 
       { 
        assignToTarget(translation); 
       } 
      } 
     } 

을하지만 당신은 단순히 람다를 제거하고 기능이 필요할 때 사용하는 번역 된 문자열을 반환 할 경우는더 좋을 것이다. 완벽을 기하기 위해이 함수를 호출하면 다음을 사용할 수 있습니다 :

Translate(k=>textBox1.Text=k,sectionKeyName); 
+0

문자열을 반환하는 간단한 함수를 사용할 것이라고 생각하지만 교육용으로 Action 을 사용하여 함수를 호출하는 방법을 보여 줄 수 있습니까? 감사 ! –

+0

@Alex 답변을 업데이트했는지 확인하십시오. –