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,我将无法使用该方法,因为属性不能通过引用传递.... 带有字段/变量....

请帮助我找到一种方法来编写一个可以处理我所有案例的方法......

//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;
}

谢谢 !!!

4

1 回答 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);
                }
            }
        }

但如果您简单地删除 lambda 并让函数返回翻译后的字符串以在需要时使用会更好。为了完整起见,要调用此函数,您可以使用:

Translate(k=>textBox1.Text=k,sectionKeyName);
于 2012-07-05T12:33:47.643 回答