【发布时间】:2013-07-24 16:14:21
【问题描述】:
关于使用两个变量的最佳方法,我有一个非常简短的问题。本质上,我有一个 enum 和一个 int,我想在几个 if 中得到它的值。我应该在 if 之外还是在内部声明它们 - 考虑以下示例:
例如:
public void test() {
EnumName? value = null;
int distance = 0;
if(anotherValue == something) {
distance = 10;
value = getValue(distance);
}
else if(anotherValue == somethingElse) {
distance = 20;
value = getValue(distance);
}
if (value == theValueWeWant){
//Do something
}
或
例如2
public void test() {
if(anotherValue == something) {
int distance = 10;
EnumType value = getValue(distance);
if (value == theValueWeWant){
//Do something
}
else if(anotherValue == somethingElse) {
int distance = 20;
EnumType value = getValue(distance);
if (value == theValueWeWant){
//Do something
}
}
我只是好奇哪个最好?或者是否有更好的方法?
【问题讨论】:
-
两者是不同的场景,第一个示例需要 if 语句之外的变量,而第二个示例则不需要 if 语句范围之外的变量
标签: c# optimization coding-style