【问题标题】:How to use namespace for a limited part of the code如何为代码的有限部分使用命名空间
【发布时间】:2019-11-12 19:52:51
【问题描述】:

我想使用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 (var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider()) {...}?您所要做的就是输入全名 - System.Security.Cryptography.MD5CryptoServiceProvider - 一次。
  • 不确定你想要什么,但也许你可以将你的课程分成几个文件(每个使用partial class),然后在每个文件中你可以使用自己的一组usings跨度>
  • 不是您要查找的内容,但您可以使用完全限定名称,例如“new System.Security.Cryptography.MD5CryptoServiceProvider()”,以获得类似的效果。
  • @DmitryBychenko 如果我会这样做,我将不必在程序顶部写(using system 所在的位置)using System.Security.Cryptography;?
  • @avivgood2: 是的,如果你输入new System.Security.Cryptography.MD5CryptoServiceProvider()不必写 using System.Security.Cryptography;

标签: c# namespaces using


【解决方案1】:

我建议使用全名 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;

【讨论】:

    【解决方案2】:

    投入使用,或者直接使用例如:

    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);
     }
    

    希望你现在得到它:)

    【讨论】:

    • 试过了,不行。错误:'MD5' does not contain a definition for 'MD5.CryptoService.Provider'
    猜你喜欢
    • 2014-10-25
    • 2011-03-09
    • 2010-10-19
    • 2011-06-01
    • 1970-01-01
    • 2017-05-24
    • 2023-03-31
    • 2010-11-16
    • 2013-01-02
    相关资源
    最近更新 更多