我有一个具有[key]
属性的ViewModel,我想从该视图模型的实例中获取该属性。
我的代码看起来像这样(虚构的模型)
class AddressViewModel
{
[Key]
[ScaffoldColumn(false)]
public int UserID { get; set; } // Foreignkey to UserViewModel
}
// ... somewhere else i do:
var addressModel = new AddressViewModel();
addressModel.HowToGetTheKey..??
所以我需要从ViewModel获取UserID
(在本例中)。我怎么能这样做?
答案 0 :(得分:8)
如果您对示例中的任何代码感到困惑或困惑,只需删除评论,我就会尝试提供帮助。
总之,您有兴趣使用 Reflection 来遍历该类型的元数据,以获取分配了给定属性的属性。
以下只是一种方式(有许多其他方法以及提供类似功能的许多方法)。
取自我在评论中链接的this question:
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);
}
}
与Jon说的一样,处理多个KeyAttribute
声明以避免问题。此代码还假设您正在装饰public
属性(不是非公共属性或字段)并且需要System.Reflection
。
答案 1 :(得分:2)
您可以使用反射来实现此目的:
AddressViewModel avm = new AddressViewModel();
Type t = avm.GetType();
object value = null;
PropertyInfo keyProperty= null;
foreach (PropertyInfo pi in t.GetProperties())
{
object[] attrs = pi.GetCustomAttributes(typeof(KeyAttribute), false);
if (attrs != null && attrs.Length == 1)
{
keyProperty = pi;
break;
}
}
if (keyProperty != null)
{
value = keyProperty.GetValue(avm, null);
}