我不认为这是可能的,但似乎您可以通过某种方式创建和填充“错误”类型的 C# 数组。
我今天在 Unity 4.2.1 中偶然发现了以下异常:
Editor[] editors = ActiveEditorTracker.sharedTracker.activeEditors;
Debug.Log(editors.GetType().Name);
Debug.Log(editors.GetType().GetElementType().Name);
Debug.Log(typeof(Editor).IsAssignableFrom(editors[0].GetType()));
Debug.Log(typeof(Editor).IsAssignableFrom(editors.GetType().GetElementType()));
它打印以下输出:
MonoBehaviour[]
MonoBehaviour
True
False
在Unity中,类“MonoBehaviour”和“Editor”是不相关的slibbings(两者都继承自UnityEngine.Object,但都不继承自另一个)。它们不能相互分配或以任何方式关联,我认为这将使上述输出成为可能。
所以我的问题是:见鬼?
更详细的问题:如何创建一个“错误”类型的数组并用“正确”类型的元素填充它?我也想做这个!如何绕过 C# 中的数组检查? (也许使用不安全()?)
我目前的直觉是,C# 只能防止写入 到错误的数组(通过 ArrayTypeMismatchException),但如果你以某种方式神奇地填充数组(在 Unity 的情况下,可能使用黑暗的 C++ 魔法), 它只是有效..?
(也很有趣:如果我这样做 editors[0] = editors[0]
我会得到提到的 ArrayTypeMismatchException)
编辑:也很有趣:Array self = editors; editors = (Editor[])self;
抛出一个 InvalidCastException
最佳答案
一些魔法
Editor[] editors = ActiveEditorTracker.sharedTracker.activeEditors;
Editor e0 = editors[0];
Editor e1 = editors[1];
Editor e2 = editors[2];
Editor[] test = {e0, e1, e2};
Debug.Log(test.GetType());
Debug.Log(typeof(Editor).IsAssignableFrom(test[0].GetType()));
Debug.Log(typeof(Editor).IsAssignableFrom(test.GetType().GetElementType()));
UnityEditor.Editor[] UnityEngine.Debug:日志(对象)
是的 UnityEngine.Debug:日志(对象)
是的 UnityEngine.Debug:日志(对象)
关于错误类型的 C# 数组可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18914222/