gpt4 book ai didi

c# - 为 int、float 等类型分配额外的属性以进行反射

转载 作者:行者123 更新时间:2023-11-30 14:21:48 26 4
gpt4 key购买 nike

我正在尝试自动显示位于 Unity 特定脚本中的变量(通过反射收集)。问题在于分配自定义值(例如:“string DisplayName”、“bool DisplayMe”、“bool WriteMe”等)。当谈到我的自定义类时,我知道我会怎么做,但我想避免为此目的重新制作 float、string、int 等类型。

例如,假设我有:

public class myBaseClass
{
public string Name = "Display Name";
public bool AmReadable = true;
public bool AmWritable = true;
}

然后:

public class myDoubleFloat: myBaseClass
{
public float ValueFirst;
public float ValueSecond;
}

所以在Unity的一些脚本中我定义了它:

public class SomeScriptOnGameObject : MonoBehaviour
{
public myDoubleFloat myFirstVariable{get; set;}
public float mySecondVariable{get; set;}
}

所以稍后通过反射(reflection)我可以检查是否应该读取“myFirstVariable”,它的显示名称等 - 而对于“mySecondVariable”我无法执行此检查。如何在不重新发明轮子并为每种类型(如 float、string、int、List 等)创建类的情况下解决这个问题?

最佳答案

您可以定义一个通用包装器:

public class MyProperty<T>
{
private T _value;

public T Get() => _value;

public T Set(T newValue) => _value = newValue;

public string Name { get; set; }

public bool AmReadable { get; set; }

public bool AmWritable { get; set; }
}

并使您的属性的 getter 和 setter 映射到一些类型为 MyProperty<T> 的支持字段:

public class SomeScriptOnGameObject : MonoBehaviour
{
private MyProperty<MyDoubleFloat> _myFirstVariable;

private MyProperty<float> _mySecondVariable;

public MyDoubleFloat MyFirstVariable
{
get => _myFirstVariable.Get();
set => _myFirstVariable.Set(value);
}

public float MySecondVariable
{
get => _mySecondVariable.Get();
set => _mySecondVariable.Set(value);
}

public SomeScriptOnGameObject()
{
_myFirstVariable = new MyProperty<MyDoubleFloat>
{
//configuration
};

_mySecondVariable = new MyProperty<float>
{
//configuration
};
}
}

如果你想花哨一点,你甚至可以添加一个隐式运算符来摆脱 Get()并制作任何 T可从 MyProperty<T> 分配:

    public class MyProperty<T>
{
private T _value;

public T Set(T newValue) => _value = newValue;

public string Name { get; set; }

public bool AmReadable { get; set; }

public bool AmWritable { get; set; }

public static implicit operator T(MyProperty<T> myProperty) =>
myProperty != null ? myProperty._value : default;
}

和:

  public MyDoubleFloat MyFirstVariable
{
get => _myFirstVariable;
set => _myFirstVariable.Set(value);
}

关于c# - 为 int、float 等类型分配额外的属性以进行反射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52843268/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com