我可以在方法范围内用 C# 或 VB.NET 创建别名吗?

发布于 2024-09-01 02:36:26 字数 210 浏览 4 评论 0原文

是否有等同于别名语句的东西,例如:

// C#:
using C = System.Console;

或:

' VB.NET '
Imports C = System.Console

...但是在方法范围内 - 而不是应用于整个文件?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

沧笙踏歌 2024-09-08 02:36:26

虽然这可能有点矫枉过正,但您可以创建一个分部类,并仅将您希望别名应用到的函数与别名一起放置在它们自己的文件中。

在主类文件中:

/*Existing using statements*/   

namespace YourNamespace
{
    partial class Foo
    {

    }
}

在其他文件中:

/*Existing using statements*/   
using C = System.Console;

namespace YourNamespace
{
    partial class Foo
    {
        void Bar()
        {
            C.WriteLine("baz");
        }
    }
}

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");
        }
    }
}
深爱成瘾 2024-09-08 02:36:26

使用对象引用将是合乎逻辑的方式。使用静态类设置了一些障碍。像这样解决:

   var c = Console.Out;
   c.WriteLine("hello");
   c.WriteLine("world");

或者 VB.NET With 语句:

    With Console.Out
        .WriteLine("hello")
        .WriteLine("world")
    End With

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
岁月无声 2024-09-08 02:36:26

请参阅此处此处了解更多详细信息。

例子:

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{}
        }
    }
}

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{}
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文