什么是指向一个静态方法在非静态类

什么是指向一个静态方法在非静态类

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

问题描述

我听不太懂用下面的代码的根本错误:

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?");

这会说我不能访问非静态的情况下,但试验与主静态方法是静态的,是什么参考?

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();

这篇关于什么是指向一个静态方法在非静态类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 08:02