【发布时间】:2009-12-15 21:28:59
【问题描述】:
如果我通过MetadataType attribute 将属性应用于部分类,则无法通过Attribute.IsDefined() 找到这些属性。有人知道为什么,或者我做错了什么吗?
下面是我为此创建的一个测试项目,但我真的在尝试将自定义属性应用于 LINQ to SQL 实体类 - 例如 this answer in this question。
谢谢!
using System;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
namespace MetaDataTest
{
class Program
{
static void Main(string[] args)
{
PropertyInfo[] properties = typeof(MyTestClass).GetProperties();
foreach (PropertyInfo propertyInfo in properties)
{
Console.WriteLine(Attribute.IsDefined(propertyInfo, typeof(MyAttribute)));
Console.WriteLine(propertyInfo.IsDefined(typeof(MyAttribute), true));
Console.WriteLine(propertyInfo.GetCustomAttributes(true).Length);
// Displays:
// False
// False
// 0
}
Console.ReadLine();
}
}
[MetadataType(typeof(MyMeta))]
public partial class MyTestClass
{
public string MyField { get; set; }
}
public class MyMeta
{
[MyAttribute()]
public string MyField { get; set; }
}
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : System.Attribute
{
}
}
【问题讨论】:
-
看看这个,我已经在这里回答了这个问题stackoverflow.com/a/24757520/3050647
-
看看这个,我已经在这里回答了这个问题stackoverflow.com/a/24757520/3050647
标签: c# linq-to-sql attributes metadata custom-attributes