2012-10-11 78 views
4

我有一个ViewModel,它具有[key]属性,我想从该视图模型的实例中获取该属性。从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(在这种情况下)。我怎样才能做到这一点?

+1

你想使用反射来走视图模型实例的属性和查询每个'PropertyInfo'的自定义属性,看看'KeyAttribute'上存在。 [这个问题](http://stackoverflow.com/questions/390594/c-sharp-setting-property-values-through-reflection-with-attributes)涵盖了这个话题。 –

+1

您还需要考虑如果'KeyAttribute'注释多个属性会发生什么情况。 – Jon

回答

6

如果您遇到困难或与示例中的任何代码混淆,只需放下评论,我会尽力提供帮助。

总之,你是在使用反射走类型的元数据,以获得已给定的属性分配给它们的属性有趣。

以下仅仅是其中一个这样做的方式(还有很多其他方法以及提供类似功能的许多方法)。

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); 
    } 
} 

像乔恩说,处理多个KeyAttribute声明,以避免问题。此代码还假定您正在装修public属性(而非非公共属性或字段)并要求System.Reflection

+0

谢谢,它的工作:) – w00

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); 
      }