代码之家  ›  专栏  ›  技术社区  ›  Tim Hutchison

通过反射设置对象属性的对象属性

  •  0
  • Tim Hutchison  · 技术社区  · 7 年前

    我曾经 this 使用对象的反射来检索对象的反射。我检索到的属性是另一个具有名为 Value 我需要访问它。我使用反射检索的所有潜在对象都来自同一个类 EntityField 因此所有人都有一个 价值 所有物我看到了 this 所以这个问题暗示了我怎样才能访问 价值 价值 反射检索到的对象上的属性?

    我的尝试

    var parent = entity.GetType().GetProperty("Property");
    parent.GetType().GetProperty("Value").SetValue(parent, newValue);  // parent.GetType() is null
    (parent as EntityField<T>).Value = newValue;  // Not sure how to dynamically set T since it could be any system type
    

    Main(原始代码)

    private static void SetValues(JObject obj, EntityBase entity)
    {
        // entity.GetType().GetProperty("Property") returns an EntityField Object
        // I need to set EntityField.Value = obj["Value"] 
        // Current code sets EntityField = obj["Value"] which throws an error
        entity.GetType().GetProperty("Property").SetValue(entity, obj["Value"], null);
    }
    

    EntityField

    public class EntityField<T> : EntityFieldBase
    {
        private Field _Field;
        private T _Value;
    
        public EntityField(Field field, T value){
            this._Field = field;
            this._Value = value;
        }
    
        public Field Field
        {
            get
            {
                return this._Field;
            }
            set
            {
                if (this._Field != value)
                {
                    this._Field = value;
                }
            }
        }
    
        public T Value
        {
            get
            {
                return this._Value;
            }
            set
            {
                if (!EqualityComparer<T>.Default.Equals(this._Value, value))
                {
                    this._Value = value;
                    this._IsDirty = true;
                }
            }
        }
    }
    
    2 回复  |  直到 7 年前
        1
  •  0
  •   Ross Miller    7 年前

    试试这个:

    entity.GetType().GetProperty("Value").SetValue(entity, obj["Value"], null);
    

    您需要在GetProperty()方法中指定属性的名称。我怀疑没有所谓的“财产”:

    编辑:在阅读完你的评论后,试试看

    entity.Property.GetType().GetProperty("Value").SetValue(entity, obj["Value"], null);
    
        2
  •  0
  •   Stevo    7 年前

    在LinqPad中尝试了以下方法,效果很好。。。

    class TestChild<T>
    {
        public T ChildProperty { get; set; }
    }
    
    class TestParent<T>
    { 
        public TestChild<T> ParentProperty { get; set; }    
    }
    
    void Main()
    {
        var instance = new TestParent<string>
        {
            ParentProperty = new TestChild<string>()
        };
    
        instance.GetType()
                .GetProperty("ParentProperty")
                .GetValue(instance)
                .GetType()
                .GetProperty("ChildProperty")
                .SetValue(instance.ParentProperty, "Value");
    
        Console.WriteLine(instance.ParentProperty.ChildProperty);
    }