当属性名称来自另一个源时,如何动态设置类的属性,而不使用C#4中的反射(使用动态) [英] How to dynamically set a property of a class without using reflection (with dynamic) in C# 4 when property name is coming from another source
问题描述
我在运行时构建/更新EntityFramework EntityObject。我想设置实体类的属性,属性名称和值来自另一个来源。
I'm building/updating an EntityFramework EntityObject on runtime. I want to set the properties of the entity class, property names and values are coming from another source.
所以我这样做;
public static EntityCollection<T> UpdateLocaleEntity<T>(EntityCollection<T> entityCollectionToUpdate, params ILocaleControl[] values) where T : EntityObject
{
foreach (var x in entityCollectionToUpdate)
{
Type t = typeof(T);
dynamic localeEntity = x;
string cultureCode = localeEntity.CultureCode;
for (int j = 0; j < values.Length; j++)
{
var value = values[j].GetLocaleValue(cultureCode);
t.GetProperty(values[j].EntityPropertyName).SetValue(localeEntity, value, null);
}
}
return entityCollectionToUpdate;
}
那么,如何摆脱t.GetProperty ] .EntityPropertyName).SetValue(localeEntity,value,null);
So, how can I get rid of "t.GetProperty(values[j].EntityPropertyName).SetValue(localeEntity, value, null);" part, is there a dynamic way of doing this?
类似于
dynamicCastedLocaleEntity.GetProperty(values [ j] .EntityPropertyName)= value;
dynamicCastedLocaleEntity.GetProperty(values[j].EntityPropertyName) = value;
感谢。
推荐答案
恐怕不是。任何使用动态
对象都是在编译时烘焙的。任何在运行时可能变化的调用必须使用反射。
I'm afraid not. Any use of a dynamic
object is baked-in at compile time. Any call which could vary at run-time has to be done using reflection.
这篇关于当属性名称来自另一个源时,如何动态设置类的属性,而不使用C#4中的反射(使用动态)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!