C# · 12月 28, 2021

c# – 如何知道本机方法是否安全/不安全?

我实现这个功能: GetSystemPowerStatusEx& GetSystemPowerStatusEx2

根据这篇文章MSDN,我应该根据我将使用的函数创建一个类,但我的问题是:我该如何知道我应该在哪个类中放置GetSystemPowerStatusEx& GetSystemPowerStatusEx2?

我迷路了…

感谢帮助.

[编辑]我的问题是:这三个类名中哪一个对我来说是好的(NativeMethods / SafeNativeMethods / UnsafeNativeMethods)?

These methods should be in one of the following classes:

NativeMethods – This class does not
suppress stack walks for unmanaged
code permission.
(System.Security.SuppressUnmanagedCodeSecurityAttribute
must not be applied to this class.)
This class is for methods that can be
used anywhere because a stack walk
will be performed.

SafeNativeMethods – This class
suppresses stack walks for unmanaged
code permission.
(System.Security.SuppressUnmanagedCodeSecurityAttribute
is applied to this class.) This class
is for methods that are safe for
anyone to call. Callers of these
methods are not required to perform a
full security review to make sure that
the usage is secure because the
methods are harmless for any caller.

UnsafeNativeMethods – This class
suppresses stack walks for unmanaged
code permission.
(System.Security.SuppressUnmanagedCodeSecurityAttribute
is applied to this class.) This class
is for methods that are potentially
dangerous. Any caller of these methods
must perform a full security review to
make sure that the usage is secure
because no stack walk will be
performed.

解决方法 这是一个非常愚蠢的警告,最终是无效的.但保持快乐很简单,只需在您的项目中添加一个静态类,即NativeMethods,并将[DllImport]声明放在其中.不需要单独的课程.向内部声明.

请注意,您不能在仿真器上调用这些函数,测试它们将要求在设备本身上运行它们.为了让你的程序在仿真器中可调试,请务必使用#ifdef DEBUG打包调用它们的代码.