控制台是C#中的类,但可用作对象?

时间:2019-02-14 12:38:40

标签: c# class object

据我所知,要访问任何函数,方法或类的成员,我们需要使用其相应的对象,但是在C#中,我们通常使用不带任何对象的Console类来访问其功能,例如:

Console.WriteLine();

那么,这是什么原因。我对没有任何对象的直接使用Console类感到困惑。请,如果有人可以帮助,请为我解决这个难题。

2 个答案:

答案 0 :(得分:-1)

WriteLine是静态方法,静态方法属于类而不是类的对象。

答案 1 :(得分:-2)

WriteLine()static,可以通过其类名Console来调用。

在此示例中,必须在类的实例上调用Method()

public class ExampleClass
{
    public static void StaticFunction()
    {
        Console.WriteLine("You can call me from my class-name");
    }

    public void Method()
    {
        Console.WriteLine("I'm called on an object.");
    }
}

public static void Main(string[] args)program..
{
    ExampleClass.StaticFunction();

    ExampleClass exampleObject = new ExampleClass();

    exampleObject.Method();
}