實際上我甚至無法確切地說如何正確調用這個東西,但我需要一些可以在一個方法中分配變量/屬性/字段的東西。我會盡量解釋...... 我有以下代碼: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