我一直在尝试使用已在接口中声明的属性的属性。
假设:
[AttributeUsage(AttributeTargets.Property, Inherited=true)]
class My1Attribute : Attribute
{
public int x { get; set; }
}
interface ITest
{
[My1]
int y { get; set; }
}
class Child : ITest
{
public Child() { }
public int y { get; set; }
}
现在,根据我的读法,带继承= true的GetCustomAttribute()应返回继承的属性,但看起来它不起作用。
Attribute my = typeof(Child).GetProperty("y").GetCustomAttribute(typeof(My1Attribute), true); // my == null
为什么不起作用?以及如何获取属性?
答案 0 :(得分:1)
Child
没有任何自定义属性,ITest
包含这些属性,因此您必须在GetCustomAttributes
的成员上致电ITest
。
继承和实现之间存在差异。如果Child
派生自某个具有y
属性的My1Attribute
属性的基类,则继承会很好。
在您的情况下,Child
实现 ITest
,而ITest
是继承层次结构之外的其他类型。
void Main()
{
var my1Attribute = typeof(ITest).GetProperty("y").GetCustomAttribute(typeof(My1Attribute)) as My1Attribute;
Console.WriteLine(my1Attribute.x); // Outputs: 0
}
[AttributeUsage(AttributeTargets.Property, Inherited = true)]
class My1Attribute : Attribute
{
public int x { get; set; }
}
interface ITest
{
[My1]
int y { get; set; }
}
class Child : ITest
{
public Child() { }
public int y { get; set; }
}
答案 1 :(得分:0)
这只是草图,而不是详细的答案。它应该从Child
开始,了解如何找到属性。
您可以使用typeof(Child).GetInterfaces()
获取一个数组,您可以从中看到Child
实现ITest
。假设t
是你从数组中得到的typeof(ITest)
,那么:
typeof(Child).GetInterfaceMap(t)
会为您提供一个结构("地图"),以便从get
(get_y
中查看属性获取者(Child
访问者).TargetMethods
的内容)对应于界面(.InterfaceMethods
)。答案是另一个get_y
当然。您拥有的是MethodInfo
中get
属性y
访问者的ITest
。要查找房产本身,请参阅例如this answer to Finding the hosting PropertyInfo from the MethodInfo of getter/setter。获得属性信息后,请检查其自定义属性,以查找My1Attribute
及其值x
。