繁体   English   中英

反射:获取/设置属性的PropertyType的属性的值

[英]Reflection: Get/Set Value of Property's PropertyType's Property

因此,我仍然将读取的数据自动化到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));

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

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

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));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM