可能是错误类型的C#数组吗?
我不认为这是可能的,但似乎您可以以某种方式创建并填充“错误”类型的C#数组 今天,我在Unity 4.2.1中偶然发现了以下异常情况:可能是错误类型的C#数组吗?,c#,arrays,unity3d,C#,Arrays,Unity3d,我不认为这是可能的,但似乎您可以以某种方式创建并填充“错误”类型的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).Is
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中,类“MonoBehavior”和“Editor”是不相关的滑动(都继承自UnityEngine.Object,但都不继承自另一个)。它们不可相互分配,也不以任何方式相关,我可以看出这将使上述输出成为可能
所以我的问题是:见鬼
更详细的问题:如何创建一个“错误”类型的数组并用“正确”类型的元素填充它?我也想这么做!如何从C#绕过数组检查?(可能使用不安全的()
我目前的直觉是,C++只是阻止错误数组(通过AddiaType),但是如果你神奇地填充了数组(如果是Unity,可能使用暗C++魔法),它只是工作……/P> (同样有趣的是:如果我这样做
editors[0]=editors[0]
我会得到前面提到的ArrayTypeMismatchException)
编辑:也很有趣:Array self=editors;编辑器=(编辑器[])self
抛出一个无效的CastException
一些魔法
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:Log(Object)当
editors[0]
具有可分配给Editor
(您的“True”输出)的类型时,为什么分配editors[0]=editors[0]
会抛出ArrayTypeMismatchException
?代码ArraySelf=editors;编辑器=(编辑器[])self你:我也想这么做!做这件事的一个方法是在家里。您只需将Evil
中的字段类型从string
(该示例使用)更改为Editor[]
。之后,您可以将任何对象放入编辑器[]
引用中。讨厌。当编辑器[0]具有可分配给编辑器的类型(您的“True”输出)时,为什么分配编辑器[0]=编辑器[0]会抛出ArrayTypeMismatchException,因为数组本身的运行时类型不是Editor[],而是MonoBehavior[](其ElementType是MonoBehavior)。赞成。。我知道这里有些可疑的东西,但我眼前就有。。我的变量“editors”的静态类型与运行时类型不匹配:-OWill代码数组self=editors;编辑器=(编辑器[])self;运行时异常也会失败吗?是的,它抛出一个InvalidCastException
。这对我来说是一种安慰——至少是我所期待的:-DIt工作得很好,现在它是一个编辑器数组,而不是单行为数组。