You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 07:03:30