加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何返回可为空的结构?

发布时间:2020-12-16 01:27:44 所属栏目:百科 来源:网络整理
导读:我有一个方法,我想返回PrefabItem或null.但是,当我执行以下操作时,出现错误: Cannot convert null to ‘PrefabItem’ because it is a non-nullable value type struct PrefabItem { }public class A { int prefabSelected = -1; private static ListPrefab
我有一个方法,我想返回PrefabItem或null.但是,当我执行以下操作时,出现错误:

Cannot convert null to ‘PrefabItem’ because it is a non-nullable value type

struct PrefabItem { }

public class A {
  int prefabSelected = -1;
  private static List<PrefabItem> prefabs = new List<PrefabItem>();

  private PrefabItem GetPrefabItem() {
    if (prefabSelected > -1) {
      return prefabs[prefabSelected];
    }
    return null;
  }
}

我看到我可以使用Nulllable< T>,但是当我这样做时,我收到相同的消息.

struct PrefabItem { }

struct Nullable<T> {
  public bool HasValue;
  public T Value;
}

public class A {
  int prefabSelected = -1;
  private static Nullable<List<PrefabItem>> prefabs = new Nullable<List<PrefabItem>>();

  private PrefabItem GetPrefabItem() {
    if (prefabSelected > -1) {
      return prefabs.Value[prefabSelected];
    }
    return null;
  }
}

我需要做什么才能让我的方法返回PrefabItem或null?

解决方法

你应该返回Nullable< PrefabItem>还是PrefabItem?

无效语法示例:

private PrefabItem? GetPrefabItem() {
    if (prefabSelected > -1) {
      return prefabs[prefabSelected];
    }
    return null;
  }

还有一条评论.如果您需要无效元素列表,则列表的声明应该是:

private static List<PrefabItem?> prefabs = new List<PrefabItem?>();

要么

private static List<Nullable<PrefabItem>> prefabs = new List<Nullable<PrefabItem>>();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读