Is the class NativeMethods handled specially in .NET?

倾然丶 夕夏残阳落幕 提交于 2019-12-01 03:20:17

It's a convention, not a requirement. If you reflect into the CLR and take a look at code in there, you'll often see P/Invoke code inside a NativeMethods class. I believe that FxCop will recommend putting your P/Invoke code in a class like this if it encounters it.

It's just a convention that says you should place p/invoke methods in classes named *NativeMethods, but there is no technical constraint to prevent you from doing it your own way...

You can name your classes that way, but you will continue to get the code analysis warning CA1060. This warning indicates you are not following the convention. So to prevent this warning, you need to follow the convention when naming classes that have P/Invoke methods. If you want to categorize your P/Invoke methods, you can use namespaces. For example:

  • MyProject.Com.NativeMethods
  • MyProject.User32.NativeMethods
  • MyProject.OleStorage.NativeMethods

They aren't handled specially by the CLR. It's simply recommended practice to have your P/Invokes inside a class named NativeMethods, SafeNativeMethods, or UnsafeNativeMethods.

You'll see this recommendation come into play if you run FxCop on your assemblies.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!