C#:import" local"参考图书馆?

时间:2015-01-02 08:27:57

标签: c# .net syntax

这应该是一个非常简单的问题,但搜索答案却很难。

在Python中,您可以以两种(主要)方式导入库:

import myLibrary
thisObject = myLibrary.myObject()

或者:

from myLibrary import myObject
thisObject = myObject

现在,在C#中,您通常使用using来完成或多或少相同的事情:

using System;

但是,请注意Python中的第二个选项允许我们编写的代码不包含对相关对象的完整命名空间路径引用。

一旦你开始深入研究.NET,就会有一些深深埋藏的类。这可以使一些"凌乱"代码。

using System;
System.Security.Cryptography.X509Certificates.PublicKey k1 = new System.Security.Cryptography.X509Certificates.PublicKey(...);
System.Security.Cryptography.X509Certificates.PublicKey k2 = new System.Security.Cryptography.X509Certificates.PublicKey(...);

我希望我能做的就是这样的事情(伪代码):

using PublicKey from System.Security.Cryptography.X509Certificates;
PublicKey k1 = new PublicKey(...);
...

现在,我知道导入单个特定对象可能不太可行。但至少,我们可以在本地导入整个库吗?例如,System.Security.Cryptography是一个集合。所以:

using Cryptography from System.Security;
Cryptography.X509Certificates.PublicKey k1 = new Cryptography.X509Certificates.PublicKey(...);
...

最后,这可能是不可能的,但我们可以做类似Python的事情,我们可以为导入分配更本地化的名称吗?

using Cryptography from System.Security as crypt;
crypt.AESCryptoServiceProvider acsp = new crypt.AESCryptoServiceProvider();

真正的目标只是至少具有最低可读性(和重复性较低)的代码。

感谢您的任何建议!

1 个答案:

答案 0 :(得分:2)

C#中可以用于单个类或整个命名空间。请参阅MSDN

 using PublicKey = System.Security.Cryptography.X509Certificates;
 PublicKey k1 = new PublicKey(...);

 using crypt = System.Security.Cryptography;
 crypt.AESCryptoServiceProvider acsp = new crypt.AESCryptoServiceProvider();