我有一个方法想返回 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>>();
关于c# - 如何返回可为空的结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52634888/