[英]How to insert values into the object from the dictionary? (C#, Expression)
我有一個使用反射的函數:
internal static void SetPropertiesFromDictionary(object entity, Dictionary<string, object> values)
{
var typeOfEntity = entity.GetType();
var entityProperties = typeOfEntity
.GetProperties(BindingFlags.Instance |
BindingFlags.Public |
BindingFlags.DeclaredOnly);
foreach (var pi in entityProperties)
{
values.TryGetValue(pi.Name, out var value);
if (value != null)
{
pi.SetValue(entity,value);
}
}
}
如何創建用於設置屬性的表達式,以便只能使用反射一次?
不確定要實現什么目標-優化程序或使代碼看起來更簡潔。 但是您可以考慮以下解決方案:
static void Main() {
Dictionary<string, object> testDict = new Dictionary<string, object> {
{ "TestProperty1", 1 },
{ "TestProperty2", "value2" }
};
TestClass result = JsonConvert.DeserializeObject<TestClass>(JsonConvert.SerializeObject(testDict));
}
class TestClass {
public object TestProperty1 { get; set; }
public object TestProperty2 { get; set; }
}
因此,您只需將字典序列化為一個字符串,然后將此字符串反序列化為該類型的對象即可。 訣竅是序列化為json的字典與序列化為json的對象具有相同的結構,因此您可以將相同的信息視為具有鍵值對的字典或具有屬性和值的對象。 而且您無需擔心缺失的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.