C#巴迪班/元数据与思考 [英] C# Buddy Classes / Meta Data and Reflection

查看:108
本文介绍了C#巴迪班/元数据与思考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用反射来检查,如果在给定的类属性设置了只读属性。我使用的类是MVC的视图模型(使用部分的伙伴类的元数据。

I am trying to use reflection to check if properties on a given class have a ReadOnly attribute set. The classes I am using are MVC View Models (using a partial "buddy" class for the metadata.

 public partial class AccountViewModel  
{
    public virtual Int32 ID { get; set; } 
    public virtual decimal Balance { get; set; }    

} 
[MetadataType(typeof(AccountViewModelMetaData))]
public partial class AccountViewModel  
{
    class AccountViewModelMetaData
    {
        [DisplayName("ID")]
        public virtual Int32 ID { get; set; }

        [DisplayName("Balance")]
        [DataType(DataType.Currency)] 
        [ReadOnly(true)]
        public virtual decimal Balance { get; set; }

    }
}

我要检查是否平衡有只读属性。如果我设置AccountViewModel的平衡性只读属性,我可以检索这样说:

I want to check if "Balance" has the ReadOnly property. If i set the ReadOnly attribute on the Balance property of AccountViewModel, i can retrieve it this way:

Type t = typeof(AccountViewModel);
PropertyInfo pi = t.GetProperty("Balance");  
bool isReadOnly =  ReadOnlyAttribute.IsDefined(pi,typeof( ReadOnlyAttribute);

我无法获得的属性信息,如果它是在元数据类。如何检查,如果该属性存在?我有我的所有视图模型定义的元数据类,并且需要一个通用的方法来检查的元数据类的属性。

I can't retrieve the attribute info if it is on the meta data class. How can i check if the attribute exists? I have meta data classes defined for all my view models, and need a generic way to check for attributes on meta data classes.

有什么建议?

推荐答案

该解决方案是使用 GetCustomAttributes 来获取元数据类型,并检查这些属性以及..

the solution is to use GetCustomAttributes to get MetaData types and check the properties on those as well...

Type t = typeof(MyClass);
PropertyInfo pi = t.GetProperty(PropertyName);  
bool isReadOnly = ReadOnlyAttribute.IsDefined(pi, typeof(ReadOnlyAttribute));

if (!isReadOnly)
{
    //check for meta data class.
    MetadataTypeAttribute[] metaAttr = (MetadataTypeAttribute[])t.GetCustomAttributes(typeof(MetadataTypeAttribute),true);

    if (metaAttr.Length > 0)
    {
        foreach (MetadataTypeAttribute attr in metaAttr)
        {
            t = attr.MetadataClassType;
            pi = t.GetProperty(PropertyName);

            if (pi != null) isReadOnly = ReadOnlyAttribute.IsDefined(pi, typeof(ReadOnlyAttribute));

            if (isReadOnly) break;
        }
    }
} 

这篇关于C#巴迪班/元数据与思考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆