C#:列表的抛出异常值不能为null<;int>;
当用户输入为10时,测试函数返回null。请指导我如何处理这种情况C#:列表的抛出异常值不能为null<;int>;,c#,C#,当用户输入为10时,测试函数返回null。请指导我如何处理这种情况 List<int?> test10 = testInt(9, 10).ToList(); public static List<int?> testInt(int pagetotal, int userinput) { List<int?> _data = null; if (userinput <= 10 && userinput != 0)
List<int?> test10 = testInt(9, 10).ToList();
public static List<int?> testInt(int pagetotal, int userinput)
{
List<int?> _data = null;
if (userinput <= 10 && userinput != 0)
{
if (userinput <= pagetotal)
{
_data = Enumerable.Repeat(pagetotal / userinput, userinput - 1).ToList();
int y = (pagetotal - pagetotal / userinput * (userinput - 1));
_data.Add(y);
}
}
return _data;
}
List test10=testInt(9,10).ToList();
公共静态列表测试(int pagetotal,int userinput)
{
列表_data=null;
如果(userinput\u数据
仅在所有这些条件均为真时设置为非空
值:
userinputuserinput=10(页面总数=9)。
我认为最好先规范化用户输入。
您可以添加以下行:
if(userInput > total)
userInput = total;
if(userInput <1)
userInput =1;
if(用户输入>总计)
用户输入=总数;
if(对于初学者,用户输入,如果您已经返回一个列表
,则无需对其调用ToList
)其次,如果您的userinput
值是11+或0,或者它是pagetotal
,您将返回null
。我很确定这会导致您的null
问题。在您的示例中,您使用pagetotal=9
和userinput=10
调用它,这将导致基于您的if语句的null返回s
userinput <= pagetotal
if(userInput > total)
userInput = total;
if(userInput <1)
userInput =1;