如果有`?`,则获取数组值

Ben

如果我有一个 type 变量,ReadOnlyArray<InputDevice>?我怎样才能得到第一个数组元素?

语境:

var test = playerInputActions.devices;
Debug.Log("test: " + test.GetValueOrDefault());
// Output: test: UnityEngine.InputSystem.Utilities.ReadOnlyArray`1[[UnityEngine.InputSystem.InputDevice, Unity.InputSystem, Version = 1.0.1.0, Culture = neutral, PublicKeyToken = null]]

行不通的事情:

test[0]
// Cannot apply indexing with [] to an expression of type ReadOnlyArray<InputDevice>?

test.GetValueOrDefault()[0]
// ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
// Parameter name: index
雨果

假设您指的是ReadOnlyArray<T>哪个是struct.

隐含的操作?使得它Nullable<ReadOnlyArray<T>>

写作

Nullable<ReadOnlyArray<T>> x;

ReadOnlyArray<T>? x;

基本上是完全等价的。


小背景:“他们为什么要使用可空值?”

-> 因为值类型不能null而是每个默认值总是有一个值。因此,为了表明结果无效,您可以在结构中创建一个特殊的值/属性来指示结果是否有效,或者您可以使用Nullable<T>它允许您简单地

return null; 

如果您想指示无效结果。


你想要做的是访问它Nullable<T>.Value,例如

if(test.HasValue)
// Or also
//if(test != null)
{
    var device = test.Value[0];

    ...
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章