如果我通过MetadataType attribute将属性应用于部分类,则通过Attribute.IsDefined()找不到这些属性。任何人都知道为什么,或者我做错了什么?属性。IsDefined未看到应用于MetadataType类的属性
下面是我为此创建的一个测试项目,但我真的试图将自定义属性应用于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
{
}
}
支票本了这一点,我已经回答了这里 http://stackoverflow.com/a/24757520/3050647 – elia07 2014-07-15 11:58:28
检查这个这个问题这一点,我已经在这里回答了这个问题 http://stackoverflow.com/a/24757520/3050647 – elia07 2014-07-15 12:17:19