实际上我甚至无法确切地说如何正确调用这个东西,但我需要一些可以在一个方法中分配变量/属性/字段的东西。我会尽量解释...... 我有以下代码: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;
}
谢谢你!!!
“但希望看到如何使用Lambda表达式” - 这不会有任何改进。只需使用最后一个功能变体。这很简单,重点突出。 – 2012-07-05 12:30:59