5

プロパティを持つ 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 から (この場合は) を取得する必要があります。これどうやってするの?

4

2 に答える 2

9

例のコードで行き詰まったり混乱したりした場合は、コメントを残してください。私がお手伝いします。

要約すると、リフレクションを使用して型のメタデータをたどり、特定の属性が割り当てられたプロパティを取得することに興味があります。

以下は、これを行う1 つの方法にすぎません (他にも多くの方法があり、同様の機能を提供する方法も多数あります)。

コメントでリンクしたこの質問から取得しました:

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また、このコードは、プロパティ (非公開のプロパティやフィールドではない)を装飾していることを前提としており、requires 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 に答える