C# 类默认方法
有没有办法为这样的类分配默认方法:
public class EscMenu
{
public static void EscMenu()
{
//do something
}
public static void SomeOtherMethod()
{
//do something else
}
}
因此,当我在同一解决方案的另一个类中调用 EscMenu.SomeOtherMethod();
时,它确实“做其他事情”,但我无法调用 EscMenu();
。
我怎样才能做到这一点?
谢谢!
编辑:
好的,我会尝试以更好的方式解释这一点:
我只是希望类 EscMenu
当我从另一个(外部)类调用它时执行某些操作,如下所示:EscMenu() ;
。当然,我可以轻松地在 EscMenu
中创建一个方法 default()
并在外部调用 EscMenu.default();
。但我真的很想调用 EscMenu();
如果这是不可能的,或者我仍然无法解释自己,那么请不要介意;-)
再次感谢!
Is there a way to assign a default method to a class like this:
public class EscMenu
{
public static void EscMenu()
{
//do something
}
public static void SomeOtherMethod()
{
//do something else
}
}
So when I call EscMenu.SomeOtherMethod();
in another class in the same solution, it does "do something else", but I cannot call EscMenu();
.
How can I do that?
Thanks!
EDIT:
Okay, Im gonna try to explain this in a better way:
I just want the class EscMenu
to do something when I call it from another (external) class like this: EscMenu();
. Of course I could easily create a method default()
in EscMenu
and call EscMenu.default();
externally. But I would really like to just call EscMenu();
If that just isn't possible or I continue to fail in explaining myself, then just don't mind ;-)
Thanks again!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,您不能为方法指定与其包含类型相同的名称 - 而且您确实不想将类型名称与方法名称混淆。为什么要引入歧义?
如果您可以举一些示例,说明您希望以现有方式以外的方式编写代码,我们也许可以为您提供更多帮助。 (例如,扩展方法可能可能会有所帮助。)
No, you can't give a method the same name as its containing type - and you really don't want to confuse the name of a type with the name of a method anyway. Why introduce the ambiguity?
If you could give some example where you want to write code in some way other than what's already available, we may be able to help you more. (For example, it may be that extension methods could help.)
“默认”方法的概念在 C# 中是一种荒谬,但从我从您的要求中收集到的信息来看,您不希望能够在外部调用
EscMenu
(即在class),因此为此请使用private
访问修饰符:但是您需要为该成员提供一个不同的名称。
The concept of a "default" method is a kind of absurdity in C#, but from what I can glean from your requirements, you don't want to be able to call
EscMenu
externally (i.e outside of the class), so for that use theprivate
access modifier:But you would need a distinct name for the member.
我不知道你的默认方法是什么意思。但为了防止其他类调用您的 ExcMenu 类中的方法,您可以将您的方法设为私有:
I don't knwo what you mean with default method. But to prevent other classes to call methods in your class ExcMenu, you can make your method private:
你所拥有的(如果你清理了语法)是 静态构造函数。
What you have there (if you cleaned up the syntax) is a static constructor.