非静态类中的静态方法有什么意义? [英] What is the point of a static method in a non-static class?

查看:71
本文介绍了非静态类中的静态方法有什么意义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解以下代码的潜在错误:

I have trouble understanding the underlying errors with the code below:

class myClass
{
    public void print(string mess)
    {
        Console.WriteLine(mess);
    }
}

class myOtherClass
{
    public static void print(string mess)
    {
        Console.WriteLine(mess);
    }
}

public static class Test
{
    public static void Main()
    {
        myClass mc = new myClass();
        mc.print("hello");

        myOtherClass moc = new myOtherClass();
        moc.print("vhhhat?"); 
       //This says I can't access static method in non static context, but am I not?

    }
}

我想不出为什么要在非静态类中声明静态方法,那么为什么 .NET 不会抛出异常错误.

I can't ever think of a reason why one would declare a static method in a non-static class, so why will .NET not throw an exception error.

此外,

moc.print("vhhhat?");

这会说我无法在非静态上下文中访问静态方法,但 Test 和 main 是静态的,它指的是什么?

This will say I can't access static method in non static context but Test and main are static, what is it referring to ?

推荐答案

静态类意味着您不能在非静态上下文中使用它,这意味着您不能拥有该类的对象实例化并调用该方法.如果您想使用打印方法,则必须执行以下操作:

A static class means that you cannot use it in a non-static context, meaning that you cannot have an object instantiation of that class and call the method. If you wanted to use your print method you would have to do:

myOtherClass.print("vhhhat?");

这不是静态的,因为您创建了一个名为 moc 的类的实例:

This is not static, as you created an instantiation of the class called moc:

myOtherClass moc = new myOtherClass();

这篇关于非静态类中的静态方法有什么意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆