【问题标题】:Get [key] property from ViewModel从 ViewModel 获取 [key] 属性
【发布时间】:2012-10-01 21:40:30
【问题描述】:

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

所以我需要从 ViewModel 中获取 UserID(在这种情况下)。我该怎么做?

【问题讨论】:

  • 你想使用反射来遍历 ViewModel 实例的属性,并查询每个PropertyInfo 的自定义属性以查看其上是否存在KeyAttributeThis question 涵盖了该主题。
  • 您还需要考虑如果KeyAttribute 注释多个属性会发生什么。

标签: c# annotations key


【解决方案1】:

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

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

以下只是一种方法(还有许多其他方法,也有许多提供类似功能的方法)。

取自this question我在cmets中链接:

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

【讨论】:

    【解决方案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);
               }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-19
      • 2011-11-30
      • 2014-09-06
      • 2015-02-02
      • 2020-12-07
      • 2019-11-27
      • 1970-01-01
      • 2020-02-28
      相关资源
      最近更新 更多