Get*_*awn 3 c# unity-game-engine
我有一个方法,我想要返回PrefabItem或null.但是,当我执行以下操作时,出现错误:
无法将null转换为'PrefabItem',因为它是一个不可为空的值类型
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我看到我可以使用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;
}
}
Run Code Online (Sandbox Code Playgroud)
我需要什么做的就是我的方法返回PrefabItem或null?
你应该返回Nullable< PrefabItem >或PrefabItem?
无效语法示例:
private PrefabItem? GetPrefabItem() {
if (prefabSelected > -1) {
return prefabs[prefabSelected];
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
还有一条评论.如果您需要无效元素列表,则列表的声明应该是:
private static List<PrefabItem?> prefabs = new List<PrefabItem?>();
Run Code Online (Sandbox Code Playgroud)
要么
private static List<Nullable<PrefabItem>> prefabs = new List<Nullable<PrefabItem>>();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
151 次 |
| 最近记录: |