命名空间别名:

 

如果你的类的名称恰巧和别人一样,但是两个类的命名空间不一样,那么该如何处理呢?

namespace CompanyA.AssemblyA
{
    public class Console
    {
        public static void DoA()
        {
            //just do nothing
        }
    }
}

namespace CompanyB.AssemblyB
{
    public class Console
    {
        public static void DoB()
        {
            //just do nothing
        }
    }
}

 

如果要调用的话,代码可能会是下面这个样子:

class Program
{
    static void Main(string[] args)
    {
        global::System.Console.WriteLine("test");
        CompanyA.AssemblyA.Console.DoA();
        CompanyB.AssemblyB.Console.DoB();
    }
}

 

很明显,每次都要完整的写命名空间是一件很类的事情,如果你知道命名空间别名的话,你可以这样写:

using SystemConsole = global::System;
using CA = CompanyA.AssemblyA;
using CB = CompanyB.AssemblyB;

class Program
{
    static void Main(string[] args)
    {
        SystemConsole.Console.WriteLine("test");
        CA.Console.DoA();
        CB.Console.DoB();
    }
}

 

类型别名:

 

除了对命名空间别名的话,还可以对某个具体的类别名。

using MyIntType = System.Int32;
using MyDoubleType = System.Double;
namespace CAStudy
{
    class AppStart
    {
        public static void Main()
        {
            MyIntType intType = 10;
            Console.WriteLine(intType);

            MyDoubleType doubletype = 10.0;
            Console.WriteLine(doubletype);

            Console.ReadLine();
        }
    }
}

使用了类型别名后,使用System.Int32作为参数的类型也变成了MyIntType,同样返回值也会发生改变。

using + .net 中的别名

 

using + .net 中的别名

相关文章:

  • 2022-12-23
  • 2021-08-27
  • 2021-07-21
  • 2021-09-06
  • 2021-06-11
  • 2022-12-23
  • 2021-05-25
猜你喜欢
  • 2021-11-11
  • 2022-12-23
  • 2021-11-19
  • 2021-06-21
  • 2022-12-23
  • 2022-01-28
  • 2022-12-23
相关资源
相似解决方案