Using alias indicators, we can create an alias for a type.
It is mainly used to resolve conflicts between two namespaces with the same name type or avoid redundant namespaces.
The alias indicator is defined in the outermost layer of all namespaces and has the scope of the entire unit file. If it is defined in a namespace, it takes effect only in the directly affiliated namespace.
Example:
Class1.cs:
using System;
using System.Collections.Generic;
using System.Text;
namespace com.nblogs.reonlyrun.CSharp25QExample.Example19.Lib01
{
class Class1
{
public override string ToString()
{
return "com.nblogs.reonlyrun.CSharp25QExample.Example19.Lib01's Class1";
}
}
}
Class2.cs:
using System;
using System.Collections.Generic;
using System.Text;
namespace com.nblogs.reonlyrun.CSharp25QExample.Example19.Lib02
{
class Class1
{
public override string ToString()
{
return "com.nblogs.reonlyrun.CSharp25QExample.Example19.Lib02's Class1";
}
}
}
Main Unit (program. CS ):
using System;
using System.Collections.Generic;
using System.Text;
// Use the alias indicator to resolve conflicts with the same name Type
// Defines the outermost layer of all namespaces and the scope is the entire unit file.
using Lib01Class1 = com.nblogs.reonlyrun.CSharp25QExample.Example19.Lib01.Class1;
using Lib02Class2 = com.nblogs.reonlyrun.CSharp25QExample.Example19.Lib02.Class1;
namespace Example19
{
namespace Test1
{
// Test1class1 is defined in the test1 namespace, And the scope is only within test1
using Test1Class1 = com.nblogs.reonlyrun.CSharp25QExample.Example19.Lib01.Class1;
class Class1
{
// Lib01class1 and lib02class2 can be used normally here
Lib01Class1 tmpObj1 = new Lib01Class1();
Lib02Class2 tmpObj2 = new Lib02Class2();
// Testclass1 can be used normally here
Test1Class1 tmpObj3 = new Test1Class1();
}
}
namespace Test2
{
using Test1Class2 = com.nblogs.reonlyrun.CSharp25QExample.Example19.Lib01.Class1;
class Program
{
static void Main(string[] args)
{
// Lib01class1 and lib02class2 can be used normally here
Lib01Class1 tmpObj1 = new Lib01Class1();
Lib02Class2 tmpObj2 = new Lib02Class2();
// Note that testclass1 cannot be used normally.
// Because the alias defined in the test1 namespace cannot be used in the Test2 namespace
//Test1Class1 tmpObj3 = new Test1Class1();
// Testclass2 can be used normally here
Test1Class2 tmpObj3 = new Test1Class2();
Console.WriteLine(tmpObj1);
Console.WriteLine(tmpObj2);
Console.WriteLine(tmpObj3);
Console.ReadLine();
}
}
}
}
Result:
Com. nblogs. reonlyrun. csharp25qexample. example19.lib01's class1
Com. nblogs. reonlyrun. csharp25qexample. example19.lib02's class1
Com. nblogs. reonlyrun. csharp25qexample. example19.lib01's class1