简体   繁体   English

在C#中,有没有一种方法可以将诸如Microsoft.VisualBasic.Interaction.MsgBox()之类的引用调用缩短为诸如myMsgBox()之类的引用?

[英]In C# is there a way to shorten reference calls like Microsoft.VisualBasic.Interaction.MsgBox() to something like myMsgBox()?

I'm new to c# so I apologize if this is a stupidly obvious question, or if I worded it in a bad way. 我是C#的新手,所以如果这是一个显而易见的问题,或者我用不好的方式措辞,我深表歉意。

I'm working on a VC# project that requires the use of the MsgBox() and InputBox() methods pretty frequently, and it's getting frustrating to either type the entire thing out or find it somewhere else in the code and copy-pasting it. 我正在一个VC#项目上,该项目要求非常频繁地使用MsgBox()和InputBox()方法,而让您键入整个内容或在代码中的其他位置查找并将其复制粘贴都变得令人沮丧。 First thing that came to mind is #define, but since it's a function and not a constant/variable, I'm not sure how to do that or if it's even possible. 首先想到的是#define,但是由于它是一个函数而不是常量/变量,因此我不确定该怎么做,甚至不确定。

Thanks in advance for your help. 在此先感谢您的帮助。

You could create a delegate that invokes the desired method: 您可以创建一个调用所需方法的委托:

Action<string> print = (s) => System.Console.WriteLine(s);

Usage: 用法:

print("hello");

If you are fine with just shortening the namespace and class name you can use a type alias: 如果您只需要缩短名称空间和类名,就可以使用类型别名:

using C  = System.Console;

Usage: 用法:

C.WriteLine("hello");

With C# 6.0, you can even import all the static methods from a type: 使用C#6.0,甚至可以从类型中导入所有静态方法:

using static System.Console;

Usage: 用法:

WriteLine("hello");

System.Console.WriteLine is just an here example, it works for any (static) method. System.Console.WriteLine只是一个示例,它适用于任何(静态)方法。

You can use using static if you are using C# 6: 如果使用的是C#6,则可以使用using static

using static Microsoft.VisualBasic.Interaction;

This allows to call any method of a static class (here Interaction ) without referencing it later in code again. 这允许调用静态类的任何方法(此处为Interaction ),而无需稍后在代码中再次引用它。 So with this you can call MsgBox() instead of Interaction.MsgBox() 因此,您可以调用MsgBox()而不是Interaction.MsgBox()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM