Lambda表达式/委托赋值变量

时间:2012-07-05 12:26:46

标签: c# .net 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 个答案:

答案 0 :(得分: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);
                }
            }
        }

但如果您只是删除lambda并让函数返回需要时使用的翻译字符串,那么它将更好。为了完整起见,要调用此功能,您可以使用:

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