当前位置: 首页 > 编程语言 > C#

如何获取自定义属性?Share

时间:2023-04-11 03:24:51 C#

我如何获取自定义属性?我使用2.0框架尝试了以下代码,然后我得到了一个属性,但是当我在紧凑型框架上尝试这个时,它总是返回一个空数组。MSDN文档说它支持它,我做错了什么?测试x=新测试();FieldInfofield_info=x.GetType().GetField("ArrayShorts");object[]custom_attributes=field_info.GetCustomAttributes(typeof(MarshalAsAttribute),false);[StructLayout(LayoutKind.Sequential)]publicstructTest{[MarshalAs(UnmanagedType.ByValArray,SizeConst=4)]publicushort[]ArrayShorts;编辑2所以我现在正在与CF团队核实,但我相信你发现了一个错误。这表示它更好:publicclassMyAttribute:Attribute{publicMyAttribute(UnmanagedTypefoo){}publicintBar{get;放;}}[StructLayout(LayoutKind.Sequential)]publicstructTest{[CLSCompliant(false)][MyAttribute(UnmanagedType.ByValArray,Bar=4)][MarshalAs(UnmanagedType.ByValArray,SizeConst=4)]publicushort[]ArrayShorts;}classProgram{staticvoidMain(string[]args){FieldInfofield_info=typeof(Test).GetField("ArrayShorts");object[]custom_attributes=field_info.GetCustomAttributes(typeof(MarshalAsAttribute),false);Debug.WriteLine("属性:"+custom_attributes.Length.ToString());custom_attributes=field_info.GetCustomAttributes(typeof(MyAttribute),false);Debug.WriteLine("属性:"+custom_attributes.Length.ToString());custom_attributes=field_info.GetCustomAttributes(typeof(CLSCompliantAttribute),false);Debug.WriteLine("属性:"+custom_attributes.Length.ToString());在完整的框架下,我得到了回复:属性:1Attributes:1Attributes:1根据CF3.5我得到这个:Attributes:0Attributes:1Attributes:1所以你可以看到它完全能够返回属性,自定义或BCL内部,而不是MarshalAsAttribute编辑3好的,我做了一点挖掘,结果证明如果您遵循规范,CF行为实际上是正确的。这违背了所有逻辑,但这是事实。以上是C#学习教程:HowdoIGetCustomAttributes?如果所有分享的内容对你有用,需要进一步了解C#学习教程,希望大家多多关注。本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: