将 156 个字符串传递给多个函数
Passing 156 character string to multiple functions
我有一个 c# winforms .net 4 应用程序,它接收到一条 156 个字符的消息,然后我将这条消息原封不动地依次传递给多个函数。
我的问题是,一直传递相同的值作为参数是否效率低下,还是有更有效的方法?
所以目前我有:
string code = getTheCode();
\decode first part
string result1 = getResult1(code);
string result2 = getResult2(code);
...
代码的值在初始分配后永远不会改变。
不断将相同的代码传递给多个方法可能效率不高。如果您发现必须多次执行此操作,则可能需要创建一个 class 负责 'getting results'。在这个新 class 的构造函数中传递 ''code'。这样您就可以在 class 的生命周期内重复使用 'code' 并且您不必继续传递与参数
相同的值
您可以创建一个带有构造函数的 class,该构造函数要求您将字符串作为参数传递并将其设置为私有 属性。然后,您可以使用使用此私有 属性 计算结果的方法检索数据。
但这当然只是您喜欢的编码风格的问题(以及您是否会在一处或多处使用这些方法)。对我来说,它更具可读性,而且你要确保代码变量在 ResultGetter class.
的实例中不会改变
public class ResultGetter
{
private readonly string _code;
public ResultGetter(string code)
{
_code = code;
}
public string GetResult1()
{
var returnValue = // do something with _code property
return returnValue;
}
public string GetResult2()
{
var returnValue = // do something with _code property
return returnValue;
}
// et cetera ad nauseam
}
然后在你的主文件中:
var code = getTheCode();
var rg = new ResultGetter(code);
string result1 = rg.GetResult1();
string result2 = rg.GetResult2();
答案是否定的。保持传递相同的字符串作为参数并不是低效的。您只是传递对字符串的引用,因此效率很高。
我有一个 c# winforms .net 4 应用程序,它接收到一条 156 个字符的消息,然后我将这条消息原封不动地依次传递给多个函数。
我的问题是,一直传递相同的值作为参数是否效率低下,还是有更有效的方法?
所以目前我有:
string code = getTheCode();
\decode first part
string result1 = getResult1(code);
string result2 = getResult2(code);
...
代码的值在初始分配后永远不会改变。
不断将相同的代码传递给多个方法可能效率不高。如果您发现必须多次执行此操作,则可能需要创建一个 class 负责 'getting results'。在这个新 class 的构造函数中传递 ''code'。这样您就可以在 class 的生命周期内重复使用 'code' 并且您不必继续传递与参数
相同的值您可以创建一个带有构造函数的 class,该构造函数要求您将字符串作为参数传递并将其设置为私有 属性。然后,您可以使用使用此私有 属性 计算结果的方法检索数据。
但这当然只是您喜欢的编码风格的问题(以及您是否会在一处或多处使用这些方法)。对我来说,它更具可读性,而且你要确保代码变量在 ResultGetter class.
的实例中不会改变public class ResultGetter
{
private readonly string _code;
public ResultGetter(string code)
{
_code = code;
}
public string GetResult1()
{
var returnValue = // do something with _code property
return returnValue;
}
public string GetResult2()
{
var returnValue = // do something with _code property
return returnValue;
}
// et cetera ad nauseam
}
然后在你的主文件中:
var code = getTheCode();
var rg = new ResultGetter(code);
string result1 = rg.GetResult1();
string result2 = rg.GetResult2();
答案是否定的。保持传递相同的字符串作为参数并不是低效的。您只是传递对字符串的引用,因此效率很高。