我首先使用数据库方法,并将类SalesWallboard映射到数据库表。
SalesWallboard.cs:
namespace Wallboards.DAL.SchnellDb
{
public partial class SalesWallboard
{
public int Id { get; set; }
public string StaffName { get; set; }
...
}
}我为此创建了一个MetadataType类,用于应用自定义属性。
SalesWallboardModel.cs
namespace Wallboards.DAL.SchnellDb
{
[MetadataType (typeof(SalesWallboardModel))]
public partial class SalesWallboard
{
}
public class SalesWallboardModel
{
[UpdateFromEclipse]
public string StaffName { get; set; }
...
}
}但是在我的代码中,当我使用Attribute.IsDefined检查它时,它总是抛出false。
码
var salesWallboardColumns = typeof(SalesWallboard).GetProperties();
foreach (var column in salesWallboardColumns)
{
if (Attribute.IsDefined(column, typeof(UpdateFromEclipse))) //returns false
{
...
}
}我已经核对了给here的答案。但我不明白这个例子。有人能帮我简化一下吗?
发布于 2019-02-17 15:45:26
我要感谢“elgonzo”和“thehennyy”的评论,并通过反思纠正我的理解。
我找到了我要找的here。但我不得不做一些修改如下所示。
我创建了一个方法PropertyHasAttribute
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
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;
}然后在我的代码中使用如下
码
var salesWallboardColumns = typeof(SalesWallboard).GetProperties();
foreach (var column in salesWallboardColumns)
{
var columnName = column.Name;
if (PropertyHasAttribute<SalesWallboard>(columnName, typeof(UpdateFromEclipse)))
{
...
}
}https://stackoverflow.com/questions/54733943
复制相似问题