首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >MetadataType和Attribute.IsDefined

MetadataType和Attribute.IsDefined
EN

Stack Overflow用户
提问于 2019-02-17 13:54:14
回答 1查看 115关注 0票数 0

我首先使用数据库方法,并将类SalesWallboard映射到数据库表。

SalesWallboard.cs:

代码语言:javascript
复制
namespace Wallboards.DAL.SchnellDb
{
    public partial class SalesWallboard
    {
        public int Id { get; set; }
        public string StaffName { get; set; }
        ...
    }
}

我为此创建了一个MetadataType类,用于应用自定义属性。

SalesWallboardModel.cs

代码语言:javascript
复制
namespace Wallboards.DAL.SchnellDb
{
    [MetadataType (typeof(SalesWallboardModel))]
    public partial class SalesWallboard
    {

    }

    public class SalesWallboardModel
    {
        [UpdateFromEclipse]
        public string StaffName { get; set; }
        ...
    }
}

但是在我的代码中,当我使用Attribute.IsDefined检查它时,它总是抛出false。

代码语言:javascript
复制
var salesWallboardColumns = typeof(SalesWallboard).GetProperties();
foreach (var column in salesWallboardColumns)
{
    if (Attribute.IsDefined(column, typeof(UpdateFromEclipse))) //returns false
    {
        ...
    }
}

我已经核对了给here的答案。但我不明白这个例子。有人能帮我简化一下吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-02-17 15:45:26

我要感谢“elgonzo”和“thehennyy”的评论,并通过反思纠正我的理解。

我找到了我要找的here。但我不得不做一些修改如下所示。

我创建了一个方法PropertyHasAttribute

代码语言:javascript
复制
private static bool PropertyHasAttribute<T>(string propertyName, Type attributeType)
{
    MetadataTypeAttribute att = (MetadataTypeAttribute)Attribute.GetCustomAttribute(typeof(T), typeof(MetadataTypeAttribute));
    if (att != null)
    {
        foreach (var prop in GetType(att.MetadataClassType.UnderlyingSystemType.FullName).GetProperties())
        {
            if (propertyName.ToLower() == prop.Name.ToLower() && Attribute.IsDefined(prop, attributeType))
                return true;
        }
    }
    return false;
}

我还得到了here的帮助,因为我的类型在不同的程序集中。

方法GetType

代码语言:javascript
复制
public static Type GetType(string typeName)
{
    var type = Type.GetType(typeName);
    if (type != null) return type;
    foreach (var a in AppDomain.CurrentDomain.GetAssemblies())
    {
        type = a.GetType(typeName);
        if (type != null)
            return type;
    }
    return null;
}

然后在我的代码中使用如下

代码语言:javascript
复制
var salesWallboardColumns = typeof(SalesWallboard).GetProperties();
foreach (var column in salesWallboardColumns)
{
    var columnName = column.Name;
    if (PropertyHasAttribute<SalesWallboard>(columnName, typeof(UpdateFromEclipse)))
    {
        ...
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54733943

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档