我已经使用 2.0 框架尝试了以下代码,并且我得到了一个属性,但是当我在紧凑框架上尝试这个时,它总是返回一个空数组.MSDN 文档说它支持,我做错了吗?
I have tried the following code using the 2.0 framework and I get an attribute back, but when I try this on the compact framework, it always returns an empty array. The MSDN documenation says its supported, am I doing something wrong?
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 团队核实,但我相信你发现了一个错误.这显示得更好:
So I'm checking with the CF team now but I believe you've found a bug. This shows it even better:
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());
}
}
在完整的框架下,我得到了这个:
Under the full framework I get back this:
Attributes: 1
Attributes: 1
Attributes: 1
在 CF 3.5 下我得到这个:
Under CF 3.5 I get this:
Attributes: 0
Attributes: 1
Attributes: 1
因此您可以看到它完全能够返回自定义或 BCL 中的属性,而不是 MarshalAsAttribute.
So you can see it's fully capable of returning an attribute, either custom or within the BCL, just not the MarshalAsAttribute.
编辑 3好吧,我做了更多的挖掘,结果发现 CF 行为实际上是 正确如果你按照规范进行.这违背了所有逻辑,但它是正确的.
EDIT 3 Alright, I did a little more digging, and it turns out that the CF behavior is actually correct if you go by the spec. It goes against all logic, but it's right.
这篇关于如何获取自定义属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!