简体   繁体   English

为什么我必须在不必使用关键字static时使用?

[英]Why must I use keyword static when they don't have to?

I've been trying simple experiments to learn C# methods. 我一直在尝试简单的实验来学习C#方法。 The below code simply calls playerSelection() which asks the user for a character and returns that character to Main(string[] args). 下面的代码只是调用playerSelection(),它向用户询问一个字符并将该字符返回给Main(string [] args)。 Main prints that to the console. 主要打印到控制台。 With the below code I get the following error "An object reference is required from a non-static field." 使用下面的代码我得到以下错误“非静态字段需要对象引用。”

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Threading;


namespace SimpleFunction
{
    class Program
    {
        static void Main(string[] args)
        {
        char cplayerChoice = playerSelection();
            Console.WriteLine(cplayerChoice);
        }

        char playerSelection()
        {
            Console.WriteLine("\nEnter a Character");
            char cplayerChoice = Console.ReadKey().KeyChar;
            return cplayerChoice;
        }
    }
}

Now if I add the word static like so: 现在如果我像这样添加单词static:

static char playerSelection()

it compiles and works. 它编译和工作。 I do understand static versus non...abstractly. 我确实理解静态与非......抽象。

Ok, so here is where I'm confused and the question comes. 好的,所以这里是我困惑的地方,问题来了。

I'm learning C# from a book and in that book they go through the below example to illustrate using methods: 我正在从一本书中学习C#,在那本书中,他们通过下面的例子来说明使用方法:

using System;

namespace GetinPaid
{
    class Program
    {
        static void Main(string[] args)
        {
            (new Program()).run();
        }

        void run()
        {
            double dailyRate = readDouble("Enter your daily rate:");
            int noOfDays = readInt("Enter the number of days: ");
            writeFee(calculateFee(dailyRate, noOfDays));
        }

        private void writeFee(double p)
        {
            Console.WriteLine("The consultant's fee is: {0}", p * 1.1);
        }

        private double calculateFee(double dailyRate, int noOfDays)
        {
            return dailyRate * noOfDays;
        }

        private int readInt(string p)
        {
            Console.Write(p);
            string line = Console.ReadLine();
            return int.Parse(line);
        }

        private double readDouble(string p)
        {
            Console.Write(p);
            string line = Console.ReadLine();
            return double.Parse(line);
        }
    }
}

Question: 题:

Why in their example can they call methods without using the keyword static but I have to use it? 为什么在他们的例子中他们可以在不使用关键字static的情况下调用方法但我必须使用它?

Thanks! 谢谢!

In their example, they're creating an instance of Program , and calling a method on that instance: 在他们的示例中,他们正在创建Program实例 ,并在该实例上调用方法:

(new Program()).run();

This is more cleanly written as: 这更干净地写成:

Program program = new Program();
program.run();

From within those instance methods, you can call other instance methods because you're implicitly calling them on this . 在这些实例方法中,您可以调用其他实例方法,因为您在this上隐式调用它们。

As an aside, if that really is sample code from the book, I suggest you get a different book: there are some very questionable aspects of style there. 顺便说一句,如果真的是书中的示例代码,我建议你得到一本不同的书:那里的风格有一些非常值得怀疑的方面。 In particular: 尤其是:

  • Method names should be CamelCased; 方法名称应为CamelCased; certainly for public methods but typically private too 当然对于公共方法,但通常也是私人的
  • The author is inconsistent in whether private is explicit or implicit 作者在private是明确的还是隐含的方面是不一致的
  • Method names which refer to types should usually use the CLR name rather than the C# name, eg ReadInt32 instead of readInt . 引用类型的方法名称通常应使用CLR名称而不是C#名称,例如ReadInt32而不是readInt Again, it's not as important for private methods, but it's a bad habit to get into 对于私人方法来说,它并不重要,但这是一个不好的习惯
  • Using double for currency values is a really bad idea 使用double作为货币值是一个非常糟糕的主意
  • The parameter name of p gives no information (in various places, used for different meanings) p的参数名称不提供信息(在不同的地方,用于不同的含义)
  • For user input, you'd typically use TryParse rather than Parse , and check the return value then potentially reprompt on bad input 对于用户输入,您通常使用TryParse而不是Parse ,并检查返回值然后可能在错误输入时重新启动

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

相关问题 为什么不能在.Net的静态方法中使用关键字“ this”? - Why can't you use the keyword 'this' in a static method in .Net? 我可以在C#中包含一个静态类,这样我不必键入类名即可使用其静态函数吗? - Can I include a static class in C# so I don't have to type the class name to use its static functions? 为什么我不能使用as关键字作为结构? - Why can't I use the as keyword for a struct? 我不明白为什么我们需要'new'关键字 - I don't understand why we need the 'new' keyword 为什么当我在 DataGrid 中做了一些更改时,我的 ObservableCollection 没有任何更改? - Why I don't have any changes in my ObservableCollection when I have made some in my DataGrid? 为什么我没有“ExecuteScalar”的定义? - Why don't I have a definition for 'ExecuteScalar'? 当我在Visual Studio中单击“添加项目”时,为什么没有ADO.NET? - Why I don't have ADO.NET when I click “add item” in Visual Studio? 为什么我必须使用 <T> on静态方法调用泛型类 - Why do I have to use <T> on static method call on a generic class 在个人类上使用字典时,为什么不必覆盖GetHashCode? - Why don't I ever have to override GetHashCode when using Dictionaries on personal classes? 我不明白为什么我有空 MVC AJAX - I don't understand why I have null MVC AJAX
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM