5

我有一个具有[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..??

所以我需要UserID从 ViewModel 中获取(在这种情况下)。我怎样才能做到这一点?

4

2 回答 2

9

如果您对示例中的任何代码感到困惑或困惑,只需发表评论,我会尽力提供帮助。

总之,您对使用反射来遍历类型的元数据以获取具有分配给它们的给定属性的属性很感兴趣。

以下只是执行此操作的一种方法(还有许多其他方法以及许多提供类似功能的方法)。

取自我在评论中链接的这个问题:

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.

于 2012-10-11T09:08:49.893 回答
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);
           }
于 2012-10-11T09:19:29.237 回答