在列表中添加/插入双AND字符串



所以,快。有可能在列表中插入一个双AND字符串吗?像这样:

if (input2 == 0)  // this boolean checks if the first number is devided by zero, then:
{
listOfResults.Insert(index: temp, item: "You divided by 0! Wait, thats illegal"); // and thats what i want, to add a string into the position of the list when the input is 0
}
else
{
result = (double)input1 / (double)input2; // the input numbers are int but i cast them to double 
listOfResults.Insert(index: position, item: result);
}

我的输入是:3和2,6和3,-4和0,1和2,我把第一个数字除以第二个输入数字
输出应为:

1.5
2
您除以0!等等,这是非法的
0.5
所以有可能为列表中的每个位置存储双AND字符串吗?

是的,您可以制作一个List<object>,可以包含任何数据类型、double、string、int、其他对象等。

一个更好的选择可能是定义一个Result对象,例如

class Result
{
public bool Error { get; set; } = false;
public double Value { get; set; }
public string ErrorMessage { get; set; } = "";
}

然后存储列表<Result>,这样您就不需要转换或检查类型。

您可以使用元组列表:

var tupleList = new List<(double, string)>();
tupleList.Add((2.5, "a string"));

如果你的代码是,我会这么做

var listOfResults = new List<(double? result, string error)>();
if (input2 == 0)
{
listOfResults.Insert(index: temp, item: (null, "You divided by 0! Wait, thats illegal"));
}
else
{
result = (double)input1 / input2;
listOfResults.Insert(index: position, item: (result, null));
}

以下是如何打印输出:

foreach (var item in listOfResults)
{
if (item.result.HasValue)
Console.WriteLine(item.result);
else
Console.WriteLine(item.error);
}

List将允许这两种类型。例如,在使用值时,可以使用typeof((==typeof(double(,或者简单地使用ToString((。

static void Main(string[] args)
{
List<object> myData = new List<object>()
{
1.234,
-0.1,
"divide by zero",
100.0
};
foreach (object item in myData)
{
Console.WriteLine(item.ToString());
}
}

相关内容

最新更新