在 C# 中,有没有办法将 Microsoft.VisualBasic.Interaction.MsgBox() 之类的引用调用缩短为 myMsgBox() 之类的东西?

bli*_*lla 1 c# inputbox msgbox

我是 c# 新手,所以如果这是一个愚蠢的明显问题,或者我的措辞不好,我深表歉意。

我正在开发一个 VC# 项目,该项目需要非常频繁地使用 MsgBox() 和 InputBox() 方法,并且将整个内容输入出来或在代码中的其他地方找到它并复制粘贴它变得令人沮丧. 首先想到的是#define,但由于它是一个函数而不是一个常量/变量,我不确定如何做到这一点,或者是否有可能。

在此先感谢您的帮助。

Adr*_*ian 5

您可以创建一个调用所需方法的委托:

Action<string> print = (s) => System.Console.WriteLine(s);
Run Code Online (Sandbox Code Playgroud)

用法:

print("hello");
Run Code Online (Sandbox Code Playgroud)

如果您只需缩短命名空间和类名就可以了,您可以使用类型别名:

using C  = System.Console;
Run Code Online (Sandbox Code Playgroud)

用法:

C.WriteLine("hello");
Run Code Online (Sandbox Code Playgroud)

使用 C# 6.0,您甚至可以从类型导入所有静态方法:

using static System.Console;
Run Code Online (Sandbox Code Playgroud)

用法:

WriteLine("hello");
Run Code Online (Sandbox Code Playgroud)

System.Console.WriteLine 只是一个例子,它适用于任何(静态)方法。