有关[DllImport]的疑问 [英] Doubt regarding [DllImport]
本文介绍了有关[DllImport]的疑问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好,
请参阅以下代码段....
[DllImport(" )]]
私有 静态 外部 IntPtr hWnd,
是什么意思
我的疑问不仅仅在于单词DllImport :-) c#中[]的含义是什么?
解决方案
这意味着您正在声明方法的属性声明(因此带有"["和]"部分),表示该方法不在.NET程序集中:它在标准的DLL文件中,在本例中为user32.dll
这是您要导入的函数的本机位置. User32.dll
是核心Windows dll之一,并且在其中实现了ShowWindow
.
这是一个属性 –请参见 ^ ],对它们进行了很好的介绍.
E:除了声明本身包含的普通类型系统元数据外,属性还允许您向元素中添加声明性元数据.属性通常不做任何事情,它们只是程序集中的静态信息,但是框架的各个部分(包括编译器和OS)会查看其中的某些部分(例如[过时],[可序列化],[AssemblyVersion] )并相应地更改其行为.
您可以通过继承Attribute来创建新属性,但是它们什么都不做–您需要编写代码以检查属性的元素(通常通过反射)并相应地更改逻辑.这可能会产生非常优雅的``最终用户''代码,将字段标记为例如输出数据表中的列,或打包为TCP消息等,但要以牺牲性能为代价,并且在基于属性管理逻辑的应用程序部分还需要一些相当混乱的代码.
框架使用[DllImport]来提示它解析方法时尝试加载的内容(在运行时,我认为不确定).
Hi All,
Please see the following code snippet....
[DllImport("user32.dll")]
private static extern Boolean ShowWindow(IntPtr hWnd, Int32 nCmdShow);
My doubt is what is mean by
[DllImport("user32.dll")]
My doubt is not simply on the word DllImport :-) What is the meaning of [] in c# ?
解决方案 It means that you are declaring an attribute to the method declaration (hence the ''['' and '']'' parts) which is saying that the method is not located in a .NET assembly: it is in a standard DLL file, in this case called user32.dll
It is the native location of the function that you are importing. User32.dll
is one of the core windows dlls and ShowWindow
is implemented in it.
That is an attribute – see this article[^] for a good introduction to them.
E: Attributes allow you to add declarative metadata to elements, in addition to the normal type system metadata included in the declaration itself. Attributes don''t generally do anything, they are just static information within the assembly, but various parts of the framework (including the compiler and the OS) look at some of them (e.g. [Obsolete], [Serializable], [AssemblyVersion]) and alter their behaviour accordingly.
You can create new attributes by inheriting from Attribute, but they don''t do anything – you then need to write code to inspect elements (through reflection generally) for attributes and change your logic accordingly. This can result in very elegant ''end user'' code, marking fields as e.g. columns in an output data table, or to be packaged up in a TCP message, etc, but at the cost of a bit of performance and also some rather messy code in the part of the application that manages the logic based on attributes.
[DllImport] is used by the framework to cue it on what to try to load when it resolves the method (at runtime, I think, not sure about that though).
这篇关于有关[DllImport]的疑问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文