是否可以循环具有特定DataAnnotation和特定值的属性?.NET C#

MrB*_*liz 2 .net c# asp.net-mvc data-annotations

假设我有一个自定义DataAnnotation属性的多个属性:

[Objective].
Run Code Online (Sandbox Code Playgroud)

我只想将记录放在我的viewmodel中,其值为'Y'并且用[Objective]的属性修饰

这种事可能吗?

Ste*_*ris 5

是的,可以使用反射.我为工厂实现了类似的东西来为WPF创建依赖属性.整个源代码可以在这里找到.

相关的一段代码:

// Check all properties for a dependency property attribute.
const BindingFlags ALL_PROPERTIES = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
var matchingProperties = new Dictionary<PropertyInfo, DependencyPropertyAttribute>();
foreach ( PropertyInfo property in m_ownerType.GetProperties( ALL_PROPERTIES ) )
{
    object[] attribute = property.GetCustomAttributes( typeof( DependencyPropertyAttribute ), false );
    if ( attribute != null && attribute.Length == 1 )
    {
        // A correct attribute was found.
        DependencyPropertyAttribute dependency = (DependencyPropertyAttribute)attribute[ 0 ];

        // Check whether the ID corresponds to the ID required for this factory.
        if (dependency.GetId() is T)
        {
            matchingProperties.Add(property, dependency);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

同时我已经在抽象类的层次结构中抽象了这种行为,因为我在创建工厂时做了类似的事情来简化创建视图模型,但我相信上面的代码已经回答了你的问题.这个抽象'工厂'的源代码可以在这里找到.

更新:

要访问属性的值,请使用PropertyInfo.GetValue().您将需要引用您的类的实例.