首页 > 解决方案 > 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)
    {
        if (userinput <= pagetotal)
        {
            _data = Enumerable.Repeat(pagetotal / userinput, userinput - 1).ToList();
            int y = (pagetotal - pagetotal / userinput * (userinput - 1));
            _data.Add(y);

        }
    }

    return _data;
}

标签: c#

解决方案


_datanull仅当所有这些条件都满足时才设置为非值true

  • userinput <= 10-这是true,因为userinput10
  • userinput != 0-这是true,因为userinput10
  • userinput <= pagetotal- 这是false,因为userinput10pagetotal而是9

您需要决定在pagetotal小于时返回什么userinput。目前它是null,但您可能会返回一个空列表:

if (userinput <= pagetotal) {
    ...
} else {
    _data = ...
}

推荐阅读