首页 > 解决方案 > 反射:获取/设置属性的PropertyType的属性值

问题描述

所以我仍然在将我的读取数据自动化到 UI 中(使用 Unity),情况是这样的:在 GameObject 上,我有一个脚本,我在其中存储变量/属性及其整齐排序的属性。我通过反射阅读它们,例如:

public void insertAllFromGameObject(GameObject target, List<Type> types)
{
    var components  = target.GetComponents<Component>();
    foreach (var component in components)
    {
        if(types.Contains(component.GetType()))
        {
            var properties = component.GetType().GetProperties().Where(t => t.GetCustomAttributes<ListableAttribute>().Count() > 0);
            foreach(var p in properties)
            {
                Debug.Log("VALUE: "+p.GetValue(component, null));

这行得通。现在,假设我有一个属性,我想在它的类中达到峰值,列出它的属性,而不是在这个特定属性中设置的值,并可能针对这个属性一一修改它们。

我已经列出了清单,但无法弄清楚将什么作为参数传递给 GetValue。例子:

public void insertAllFromVariable(GameObject target, List<Type> types, string propertyName)
{
    var components  = target.GetComponents<Component>();
    foreach (var component in components)
    {
        if(types.Contains(component.GetType()))
        {
            var property = component.GetType().GetProperty(propertyName);

            var propertysProperties = property.PropertyType.GetProperties().Where(t => t.GetCustomAttributes<ListableAttribute>().Count() > 0);
            foreach(var p in propertysProperties)
            {
                Debug.Log("VALUE: "+p.GetValue(component, null));

最后一行是一个问题,因为我当然不是在“组件”中寻找它(而是在组件内的属性中) - 但是我应该传递什么以便它反映我的变量值?

标签: c#unity3dreflection

解决方案


修改了您的代码,确保我没有运行代码,但您应该清楚概念:

public void insertAllFromVariable(GameObject target, List<Type> types, string propertyName)
        {
            var components = target.GetComponents<Component>();
            foreach (var component in components)
            {
                if (types.Contains(component.GetType()))
                {
                    PropertyInfo property = component.GetType().GetProperty(propertyName);
                    object theRealObject = property.GetValue(component);

                    PropertyInfo[] propertysProperties = theRealObject.GetType().GetProperties().Where(t => t.GetCustomAttributes<ListableAttribute>().Count() > 0);
                    foreach (PropertyInfo p in propertysProperties)
                    {
                        Debug.Log("VALUE: " + p.GetValue(theRealObject));

推荐阅读