在C#中能否让结构体变量指向另一结构体变量?含unsafe指针探讨
在C#中能否让结构体变量像对象那样指向另一个结构体变量?使用unsafe指针是否可行?
初始代码示例:
class IntComponent { public int size; } class IntReferenceComponent : IntComponent { public IntComponent target; // 保持我的size与target的size一致 private void OnValidate() { // 赋值target时触发 } }
编辑补充:根据方案,最终实现如下:
public abstract class StructComponent<T> where T : struct { public T size; } public class IntComponent : StructComponent<int> { } public class IntReferenceComponent : IntComponent { public IntComponent target; public new int size { get => target.size; set => target.size = value; } }
在Unity中还需创建自定义编辑器:
public abstract class StructComponentEditor<T, D> : Editor where T : struct where D : StructComponent<T> { public static object StructField(string label, T value, params GUILayoutOption[] options) { switch (value) { case Vector3 v: return EditorGUILayout.Vector3Field(label, v, options); case Vector2 v: return EditorGUILayout.Vector2Field(label, v, options); case float f: return EditorGUILayout.FloatField(label, f, options); case int i: return EditorGUILayout.IntField(label, i, options); case double d: return EditorGUILayout.DoubleField(label, d, options); case Color c: return EditorGUILayout.ColorField(label, c, options); } return null; } public void DrawDefaultStructComponent() { D target = serializedObject.targetObject as D; PropertyInfo sizeProp = target.GetType().GetProperty("size"); object value; try { value = sizeProp.GetValue(target); } catch { value = new T(); } if(sizeProp.SetMethod != null) { sizeProp.SetValue(target, StructField("Size", (T)value)); return; } StructField("Size", (T)value); } public override void OnInspectorGUI() { DrawDefaultStructComponent(); DrawDefaultInspector(); } } [CustomEditor(typeof(StructComponent<int>), true)] [CanEditMultipleObjects] public class IntComponentEditor : StructComponentEditor<int, StructComponent<int>> { }
感谢所有提供帮助的人!
内容的提问来源于stack exchange,提问作者Panakvina321
相关产品推荐
相关产品推荐

