How do I GetCustomAttributes?(如何获取自定义属性?)
问题描述
我已经使用 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.
这篇关于如何获取自定义属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何获取自定义属性?
基础教程推荐
- 如何激活MC67中的红灯 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 XML 转换为通用列表 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01