实际上,我什至不能确切地说出那个东西是如何正确调用的,但我需要一些可以在一种方法中分配变量/属性/字段的东西。我将尝试解释...我有以下代码:
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;
}
谢谢 !!!