c# - 我如何获取自定义属性?

标签 c# compact-framework attributes marshalling getcustomattributes

我已经使用 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/

相关文章:

c# - 存储库中添加和更新方法的特定实体对象

ruby - Sum 2 具有相同键的散列属性

c# - 在位图周围绘制边框

c# - C# 通知中的新行(紧凑型框架)

c# - 如何在方法中使用属性成员

python - 在给定特定索引的情况下,如何访问对象列表中的对象属性?

c# - 有没有办法将代码镜像中编写的 css 应用于 iframe 的 html 内容?

c# - 我可以覆盖 Entity Framework 查询生成器吗?

C# 如何在 Assert.AreEqual 中期待异常?

windows-mobile - 防止 Pocket-PC 进入横向模式