Can I create an alias in C# or VB.NET within method scope?
Is there any equivalent to an aliasing statement such as:
// C#:
using C = System开发者_开发问答.Console;
or:
' VB.NET '
Imports C = System.Console
...but within method scope -- rather than applying to an entire file?
While this might be overkill, you could create a partial class and place only the functions you'd like the alias to apply to in their own file with the alias.
In the main class file:
/*Existing using statements*/
namespace YourNamespace
{
partial class Foo
{
}
}
In the other file:
/*Existing using statements*/
using C = System.Console;
namespace YourNamespace
{
partial class Foo
{
void Bar()
{
C.WriteLine("baz");
}
}
}
Using an object reference would be the logical way. You are putting up a bit of an obstacle by using a static class. Worked around like this:
var c = Console.Out;
c.WriteLine("hello");
c.WriteLine("world");
Or the VB.NET With statement:
With Console.Out
.WriteLine("hello")
.WriteLine("world")
End With
See here and here for more details.
Example:
namespace PC
{
// Define an alias for the nested namespace.
using Project = PC.MyCompany.Project;
class A
{
void M()
{
// Use the alias
Project.MyClass mc = new Project.MyClass();
}
}
namespace MyCompany
{
namespace Project
{
public class MyClass{}
}
}
}
精彩评论