C# 我如何获取CustomAttributes?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1268898/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I GetCustomAttributes?
提问by SwDevMan81
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?
我已经使用 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;
}
采纳答案by ctacke
EDIT 2
编辑 2
So I'm checking with the CF team now but I believe you've found a bug. This shows it even better:
所以我现在正在与 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());
}
}
Under the full framework I get back this:
在完整的框架下,我得到了这个:
Attributes: 1
Attributes: 1
Attributes: 1
Under CF 3.5 I get this:
在 CF 3.5 下,我得到了这个:
Attributes: 0
Attributes: 1
Attributes: 1
So you can see it's fully capable of returning an attribute, either custom or within the BCL, just not the MarshalAsAttribute.
所以你可以看到它完全有能力返回一个属性,无论是自定义的还是在 BCL 内,只是不是 MarshalAsAttribute。
EDIT 3Alright, I did a little more digging, and it turns out that the CF behavior is actually correctif you go by the spec. It goes against all logic, but it's right.
编辑 3好吧,我做了更多的挖掘,结果证明 CF 行为实际上是正确的,如果你按照规范去做。这违背了所有逻辑,但它是对的。