我想在代码中动态使用Tuple
,并且必须将值 according 分配给if
语句。我有以下代码:
if(check != null)
var scoreTmpTuple = new Tuple<Guid, string, double>(
(Guid)row["sampleGuid"],
Convert.ToString(row["sampleName"]),
Convert.ToDouble(row["sampleScore"]));
else
var scoreTmpTuple = new Tuple<Guid, string, double>(
(Guid)row["exampleGuid"],
Convert.ToString(row["exampleName"]),
Convert.ToDouble(row["exampleScore"]));
在代码中,元组在if
和else
语句的内部中声明。我想声明 outside 并相应地初始化元组。
答案 0 :(得分:3)
只需显式指定类型,而不使用var:
Tuple<Guid, string, double> scoreTmpTuple;
if (check != null)
scoreTmpTuple = Tuple.Create<Guid, string, double>(Guid.NewGuid(), "hello", 3.14);
答案 1 :(得分:3)
在if语句之前声明元组。
Tuple<Guid, string, double> scoreTmpTuple;
if(check != null)
scoreTmpTuple = new Tuple<Guid, string, double>((Guid)row["sampleGuid"],Convert.ToString(row["sampleName"]), Convert.ToDouble(row["sampleScore"]));
else
scoreTmpTuple = new Tuple<Guid, string, double>((Guid)row["exampleGuid"],Convert.ToString(row["exampleName"]), Convert.ToDouble(row["exampleScore"]));
答案 2 :(得分:1)
您可以尝试三元运算符并在元组创建过程中推送分支:
var scoreTmpTuple = Tuple.Create(
(Guid)row[check != null ? "sampleGuid" : "exampleGuid"],
Convert.ToString(row[check != null ? "sampleName" : "exampleName"]),
Convert.ToDouble(row[check != null ? "sampleScore" : "exampleScore"])
);
甚至(如果我们实际上应该在"sample"
和"example"
前缀之间切换):
string prefix = check != null
? "sample"
: "example";
var scoreTmpTuple = Tuple.Create(
(Guid)row[$"{prefix}Guid"],
Convert.ToString(row[$"{prefix}Name"]),
Convert.ToDouble(row[$"{prefix}Score"])
);
答案 3 :(得分:1)
您可以这样做:
bool isChecked = check != null;
var scoreTmpTuple = new Tuple<Guid, string, double>(
isChecked ? (Guid)row["sampleGuid"] : (Guid)row["exampleGuid"],
isChecked ? Convert.ToString(row["sampleName"]) : Convert.ToString(row["exampleName"]),
isChecked ? Convert.ToDouble(row["sampleScore"]) : Convert.ToDouble(row["exampleScore"]));