【发布时间】:2014-11-15 05:27:12
【问题描述】:
我需要将SecureString 用于微软的课程,我在internet 上找到了以下代码:
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;
}
}
}
}
唯一的问题是unsafe 关键字不断向我抛出错误说Cannot use unsafe construct in safe context。
不幸的是,我找不到为什么会这样……
注意: 上面的代码在 LINQPad 中运行,但在 VS2013 中没有(使用 resharper)。
【问题讨论】:
-
我不明白为什么你需要在这里使用 unsafe,你创建了没有不安全代码的安全字符串。检查我的答案。
-
文档说你不应该使用那个构造函数。见msdn.microsoft.com/en-us/library/176bafkd(v=vs.110).aspx 使用@mybirthname 在他的回答中给出的代码
标签: c# extension-methods unsafe securestring