如何将命名空间用于代码的有限部分

How to use namespace for a limited part of the code

我想使用 namespace System.Security.Cryptography 但仅用于代码的有限部分,因此如果我尝试在定义区域之外使用命名空间的 classesfunction不会工作。我期待的结果类似于 types 中的 using 语句,但带有 namespaces.

这里是展示我想要的示例代码:

using(System.Security.Cryptography;){
// namespace can be used from now on
            using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
            {
                UTF8Encoding utf8 =new UTF8Encoding();
                byte[] data = md5.ComputeHash(utf8.GetBytes(input));
                return Convert.ToBase64String(data);
            }
}
//now namespace can not be used- error if you are trying to use it

有可能吗?怎么做?

把它放在using中,或者直接使用例如:

System.Security.Cryptography.MD5CryptoServiceProvider

那就不用用了

我的观点是:

 using (System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider())
 {
     System.Text.UTF8Encoding utf8 = new System.Text.UTF8Encoding();
     byte[] data = md5.ComputeHash(utf8.GetBytes(input));
     return Convert.ToBase64String(data);
 }

希望你现在明白了:)

我建议使用 完整限定名 System.Security.Cryptography.MD5CryptoServiceProvider 而不是 using + 短名称 (MD5CryptoServiceProvider):

  // var - let compiler derive the type
  using (var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider())
  {
      UTF8Encoding utf8 = new UTF8Encoding();
      byte[] data = md5.ComputeHash(utf8.GetBytes(input));
      return Convert.ToBase64String(data);
  }

如果你这样做,你根本就不需要输入 using System.Security.Cryptography;