我有一個庫,它依靠它接收的類的PropertyInfo(獲取和設置值)進行一堆反射工作。獲取動態對象的PropertyInfo
現在我想能夠使用動態對象,但我找不到如何獲取動態屬性的PropertyInfo。我已經檢查了替代方案,但對於那些我需要隨處更改使用PropertyInfo來獲取/設置值的人。
dynamic entity = new ExpandoObject();
entity.MyID = 1;
// - Always null
PropertyInfo p = entity.GetType().GetProperty("MyID");
// - Always null
PropertyInfo[] ps = entity.GetType().GetProperties();
// - These are called everywhere in the code
object value = p.GetValue(entity);
p.SetValue(entity, value);
是否有可能獲得或以某種方式創建的PropertyInfo只是爲了能夠使用它的GetValue()
和SetValue()
動態對象?
我無法重現這一點。你確定屬性MyID存在於實體上並且是公共的嗎? –
@DavidL對不起,我會發佈一個更好的例子。這是一種動態,所以財產只有在已經確定並且是公開的情況下才會存在。 – Danicco
請注意,它可能不是一個實際的屬性。通過將運行時綁定重定向到名稱/值字典,某些類型像「ExpandoObject」_simulate_屬性。 –