我有一个方法,我想返回PrefabItem或null.但是,当我执行以下操作时,出现错误: Cannot convert null to ‘PrefabItem’ because it is a non-nullable value type struct PrefabItem { }public class A { int prefabSelected = -
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>>();