我已经使用 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;
}
最佳答案
编辑 2
所以我现在正在与 CF 团队核实,但我相信你已经发现了一个错误。这表明它更好:
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 .这违背了所有逻辑,但却是正确的。
关于c# - 我如何获取自定义属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1268898/