输出 Attempting to call unmanaged code without permission. Caught Security Exception attempting to call unmanaged code. Attempting to call unmanaged code with permission. Hello World! Called unmanaged code with permission. 示例 2:声明式安全性 这是使用安全权限属性的同一个示例。 // DeclarativeSecurity.cs
Code
输出 Attempting to call unmanaged code without permission. Caught Security Exception attempting to call unmanaged code. Attempting to call unmanaged code with permission. Hello World! Called unmanaged code with permission.安全性和性能 .NET Framework 安全系统可以防止从网络上下载的恶意代码损坏您的计算机系统。但即使代码从不引发 SecurityException,这些安全检查也并不是没有代价的。
输出 Attempting to call unmanaged code without UnmanagedCode permission. Hello World! Called unmanaged code without UnmanagedCode permission. Attempting to call unmanaged code with permission. Hello World! Called unmanaged code with permission. 代码讨论 请注意,以上示例允许两个非托管调用都成功,即使第一个调用不具有 UnmanagedCode 权限。在使用 SuppressUnmanagedCodeSecurityAttribute 时,应使用其他安全检查以确保不会招致安全漏洞。在上面的示例中,通过在非托管调用之前添加 UIPermission 的 Demand: