我有一个 ViewModel,其中有一个[key]
属性,我想从该视图模型的实例中获取它。
我的代码看起来像这样(虚构模型)
class AddressViewModel
{
[Key]
[ScaffoldColumn(false)]
public int UserID { get; set; } // Foreignkey to UserViewModel
}
// ... somewhere else i do:
var addressModel = new AddressViewModel();
addressModel.HowToGetTheKey..??
所以我需要得到UserID
(在本例中)来自 ViewModel。我怎样才能做到这一点?
If you are stuck or confused with any of the code in the example, just drop a comment and I'll try to help.
总之,您对使用感兴趣反射遍历类型的元数据以获取分配有给定属性的属性。
下面只是one这样做的方法(还有许多其他方法以及提供类似功能的方法)。
取自这个问题我在评论中链接:
PropertyInfo[] properties = viewModelInstance.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
var attribute = Attribute.GetCustomAttribute(property, typeof(KeyAttribute))
as KeyAttribute;
if (attribute != null) // This property has a KeyAttribute
{
// Do something, to read from the property:
object val = property.GetValue(viewModelInstance);
}
}
就像乔恩说的,处理多个KeyAttribute
声明以避免出现问题。此代码还假设您正在装饰public
属性(不是非公共属性或字段)和要求System.Reflection
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)