我有简单的单元测试来重现情况:
[Test]
public void Castle_Writes_Attribute_To_Proxy()
{
var generator = new ProxyGenerator();
var proxy = generator.CreateClassProxy<MyType>();
var type = proxy.GetType();
var prop = type.GetProperty("SomeProp");
var attrs = prop.GetCustomAttributes(typeof(DescriptionAttribute), true);
Assert.That(attrs.Length, Is.Not.EqualTo(0));
}
public class MyType
{
[Description("some description here")]
public virtual string SomeProp { get; set; }
}
测试失败,因为 Castle 动态代理不写入自定义属性,
可以将父属性写入生成的代理吗?
解决方案:使用Attribute.GetCustomAttributes(...)
var attrs = Attribute.GetCustomAttributes(prop, typeof(DescriptionAttribute));