简体   繁体   English

如何在安全的上下文中使用不安全的代码?

[英]How to use unsafe code in safe contex?

I need to use SecureString for a Microsoft's class and i found the following code on the internet : 我需要将SecureString用于Microsoft的类,我在互联网上找到以下代码:

public static class SecureStringExt
{
    public static SecureString ConvertToSecureString(this string password)
    {
        if (password == null)
            throw new ArgumentNullException("password");

        unsafe //Red highlighted line
        {
            fixed (char* passwordChars = password)
            {
                var securePassword = new SecureString(passwordChars, password.Length);
                securePassword.MakeReadOnly();
                return securePassword;
            }
        }
    }
}

The only problem is that the unsafe keyword keeps throwing me error saying Cannot use unsafe construct in safe context . 唯一的问题是unsafe关键字一直让我错误说Cannot use unsafe construct in safe context Unfortunately i couldn't find why is this happening... 不幸的是我无法找到为什么会发生这种情况......

Note: The above code runs in LINQPad but not in VS2013 (with resharper). 注意:上面的代码在LINQPad中运行,但在VS2013中没有(使用resharper)。

I am not sure if you need unsafe code in that case (see answer of @mybirthname ). 在这种情况下,我不确定你是否需要不安全的代码(参见@mybirthname的回答)。

But when unsafe code is needed, it can be enabled in Project properties. 但是当需要不安全的代码时,可以在Project属性中启用它。

  • In the main menu, click Project and then <ProjectName> properties... 在主菜单中,单击Project ,然后单击<ProjectName> properties...
  • Click on the Build page. 单击Build页面。
  • Select Allow unsafe code . 选择Allow unsafe code

允许不安全的代码

Or one can specify /unsafe compiler option explicitly. 或者可以明确指定/不安全的编译器选项。

    public static SecureString GetSecureString(string password)
    {
        SecureString secureString = new SecureString();

        foreach (char c in password)
        {
            secureString.AppendChar(c);
        }

        secureString.MakeReadOnly();
        return secureString;
    }

You can make same thing without unsafe code. 没有不安全的代码你可以做同样的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM