【发布时间】:2014-03-30 13:36:25
【问题描述】:
我想为类的特定属性定义一个自定义属性。基于反射,应该可以检查属性是否使用此属性注释。第一个 Assert.AreEqual(2, infos.Length) 通过,但第二个 Assert.AreEqual(1, properties.Count) 失败,properties.Count = 0。我错过了什么?
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using System.Reflection;
namespace Test.UnitTesting.Rest.ParameteterModels
{
public class IncludableAttribute : Attribute
{
}
public class TestClass
{
[Includable]
public List<string> List1 { get; set; }
public List<string> List2 { get; set; }
public TestClass()
{
}
}
[TestClass]
public class IncludeParamaterModelTest
{
[TestMethod]
public void TestMethod1()
{
List<string> properties = new List<string>();
FieldInfo[] infos = typeof(TestClass).GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
Assert.AreEqual(2, infos.Length);
foreach (FieldInfo fi in infos)
{
if (fi.IsDefined(typeof(IncludableAttribute), true)) properties.Add(fi.Name);
}
Assert.AreEqual(1, properties.Count);
}
}
}
【问题讨论】:
标签: c# reflection custom-attributes