2012-07-05 84 views
0

实际上我甚至无法确切地说如何正确调用这个东西,但我需要一些可以在一个方法中分配变量/属性/字段的东西。我会尽量解释...... 我有以下代码:Lambda表达式/委托赋值变量

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不能使用该方法的情况下,因为属性无法按地址.... 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

“但希望看到如何使用Lambda表达式” - 这不会有任何改进。只需使用最后一个功能变体。这很简单,重点突出。 – 2012-07-05 12:30:59

回答

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

我想我会使用返回字符串的简单函数,但对于我的教育,你能告诉我怎么用动作来调用函数吗?谢谢 ! – 2012-07-05 13:00:29

+0

@亚历克斯确定我已经更新了答案 – 2012-07-05 13:02:45

相关问题