我如何获得自定义属性?
问题描述:
我已经尝试了使用2.0框架的下面的代码,并且我得到了一个属性,但是当我在紧凑框架上尝试这个时,它总是返回一个空数组。 MSDN文档说它支持,我做错了什么?我如何获得自定义属性?
Test x = new Test();
FieldInfo field_info = x.GetType().GetField("ArrayShorts");
object[] custom_attributes = field_info.GetCustomAttributes(typeof(MarshalAsAttribute), false);
[StructLayout(LayoutKind.Sequential)]
public struct Test
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public ushort[] ArrayShorts;
}
答
EDIT 2
所以我用CF团队现在正在检查,但我相信你已经发现了一个bug。这甚至更好的显示它:
public class MyAttribute : Attribute
{
public MyAttribute(UnmanagedType foo)
{
}
public int Bar { get; set; }
}
[StructLayout(LayoutKind.Sequential)]
public struct Test
{
[CLSCompliant(false)]
[MyAttribute(UnmanagedType.ByValArray, Bar = 4)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public ushort[] ArrayShorts;
}
class Program
{
static void Main(string[] args)
{
FieldInfo field_info = typeof(Test).GetField("ArrayShorts");
object[] custom_attributes = field_info.GetCustomAttributes(typeof(MarshalAsAttribute), false);
Debug.WriteLine("Attributes: " + custom_attributes.Length.ToString());
custom_attributes = field_info.GetCustomAttributes(typeof(MyAttribute), false);
Debug.WriteLine("Attributes: " + custom_attributes.Length.ToString());
custom_attributes = field_info.GetCustomAttributes(typeof(CLSCompliantAttribute), false);
Debug.WriteLine("Attributes: " + custom_attributes.Length.ToString());
}
}
下完整的框架,我回去的:
Attributes: 1
Attributes: 1
Attributes: 1
在CF 3.5我得到这个:
Attributes: 0
Attributes: 1
Attributes: 1
所以你可以看到它是完全可以胜任返回一个属性,无论是自定义还是BCL中,都不是MarshalAsAttribute。
编辑3 好吧,我做了一个小挖多,而事实证明,在CF的行为实际上是correct if you go by the spec。它违背了所有的逻辑,但它是正确的。
我正在处理我的上例中的FieldInfo。我可以尝试看看PropertyInfo是否可以工作,但我想知道为什么我的示例不起作用。 – SwDevMan81 2009-08-12 21:52:46
buo为错误:P你知道是否有工作? – SwDevMan81 2009-08-14 11:56:06
我想工作可能只是创建我自己的自定义属性(只是重新发明轮子,我猜)?由于看起来像那样工作正常。 – SwDevMan81 2009-08-14 13:08:01