从ViewModel获取[key]属性

编程入门 行业动态 更新时间:2024-10-27 02:31:26
本文介绍了从ViewModel获取[key]属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个具有[key]属性的ViewModel,我想从该视图模型的实例中获取它.

I have a ViewModel which has a [key] property and i would like to get that from an instance of that view model.

我的代码看起来像这样(虚构模型)

My code looks something like this (fictional models)

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(在这种情况下).我该怎么办?

So i need to get the UserID(in this case) from the ViewModel. How can i do this?

推荐答案

如果您对示例中的任何代码感到困惑或困惑,请添加注释,我将尽力提供帮助.

总而言之,您很有趣地使用 Reflection 遍历该类型的元数据以获得具有为其分配了给定属性的属性.

In summary, you are interesting in using Reflection to walk the meta-data of the type to get properties that have a given attribute assigned to them.

下面只是实现此目的的一种方法(有许多其他方法,也有许多提供相似功能的方法).

Below is just one way of doing this (there are many others and also many methods that provide similar functionality).

来自这个问题评论:

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.

Like Jon says, handle multiple KeyAttribute declarations to avoid issues. This code also assumes you are decorating public properties (not, non-public properties or fields) and requires System.Reflection.

更多推荐

从ViewModel获取[key]属性

本文发布于:2023-11-14 16:32:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1587966.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   ViewModel   key

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!