簡體   English   中英

通過反射設置對象屬性的對象屬性

[英]Set Object Property of Object Property by Reflection

我用這個 SO問題來使用反射來檢索對象的屬性。 我檢索的屬性是另一個對象,該對象具有我需要訪問的名為Value的屬性。 我使用反射檢索的所有潛在對象均來自同一類EntityField ,因此都具有Value屬性。 我看到了這樣的問題,它暗示了我如何能夠訪問Value屬性,但是我不能完全將正確的代碼組合在一起。 如何訪問通過反射檢索的對象的Value屬性?

我的嘗試

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

主要(原代碼)

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

實體字段

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

嘗試這個:

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

您需要在GetProperty()方法中指定屬性的名稱。 我懷疑沒有所謂的“屬性” :)

編輯:閱讀您的評論后,嘗試

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM