C# 是否可以循环遍历具有特定DataAnnotation和特定值的属性。净碳#

C# 是否可以循环遍历具有特定DataAnnotation和特定值的属性。净碳#,c#,.net,asp.net-mvc,data-annotations,C#,.net,Asp.net Mvc,Data Annotations,假设我有多个属性,其自定义DataAnnotation属性为: [Objective]. 我只想在我的viewmodel中放入值为“Y”且用属性[Objective]修饰的记录 这种事情可能吗?是的,使用反射是可能的。我为您实现了类似的功能。可以找到完整的源代码 相关代码: // Check all properties for a dependency property attribute. const BindingFlags ALL_PROPERTIES = BindingFlags.I

假设我有多个属性,其自定义DataAnnotation属性为:

[Objective].
我只想在我的viewmodel中放入值为“Y”且用属性[Objective]修饰的记录


这种事情可能吗?

是的,使用反射是可能的。我为您实现了类似的功能。可以找到完整的源代码

相关代码:

// 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);
        }
    }
}
//检查依赖项属性的所有属性。
const BindingFlags ALL_PROPERTIES=BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
var matchingProperties=new Dictionary();
foreach(m_ownerType.GetProperties中的PropertyInfo属性(所有属性))
{
object[]attribute=property.GetCustomAttributes(typeof(dependencPropertyAttribute),false);
if(attribute!=null&&attribute.Length==1)
{
//找到了正确的属性。
DependencyPropertyAttribute dependency=(DependencyPropertyAttribute)属性[0];
//检查ID是否与此工厂所需的ID相对应。
if(dependency.GetId()为T)
{
matchingProperties.Add(属性、依赖项);
}
}
}
同时,我已经在抽象类的层次结构中抽象了这个行为,因为我在创建时做了类似的事情,但我相信上面的代码已经回答了您的问题。可以使用此抽象“工厂”的源代码

更新:


要访问属性的值,请使用。当然,您需要引用类的实例。

谢谢,我可能需要一段时间来实现它,看看它是否有效,所以它可能要到明天才能被接受:)@Doozer1979:我添加了一个抽象类,您可以使用它。它可能缺少对我的库的一些依赖项,但它可能会帮助您开始。