静态关键字是什么意思? [英] What does the static keyword mean?

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

问题描述

我是C#初学者.我发现有两种方法可以编写代码并输出相同的结果.您能解释一下两者之间的区别吗?以及何时使用#1和#2?

I am a C# beginner. I found there are 2 way to write codes and output the same results. Could you explain the different between them? And when to use #1 and #2?

class Program
{
    static void Main()
    {
        Program min = new Program();
        Console.WriteLine(min.isMin(1, 2));
        Console.ReadLine();
    }

    int isMin(int value1, int value2)
    {
        int Min;
        return Min = Math.Min(value1, value2);
    }
}

#2

class Program2
{
    static void Main()
    {
        Console.WriteLine(isMin(1, 2));
        Console.ReadLine();
    }

    static int isMin(int value1, int value2)
    {
        int Min;
        return Min = Math.Min(value1, value2);
    }
}

推荐答案

#1和#2之间的区别在于,在#1中,isMin是Program类的实例成员函数,因此必须创建一个实例.程序类

The difference between #1 and #2 is that in #1, isMin is an instance member function of the class Program, therefore you have to create an instance of the Program class

 Program min = new Program()

,然后才调用实例成员函数isMin:

and only then call the instance member function isMin:

 min.isMin(..)


在#2中,isMin是Program类的静态成员函数,并且由于Main也是同一类的静态成员函数,因此您可以从Main函数直接调用isMin.


In #2, isMin is a static member function of the Program class, and since Main is also a static member function of the same class, you can make a direct call to isMin from the Main function.

两者均有效.静态函数Main是程序的入口",这意味着它首先被执行.剩下的只是面向对象的语义.

Both are valid. The static function Main is the "entry point" into the program which means it gets executed first. The rest is just Object-Oriented semantics.

编辑

为了更好地说明问题,似乎一个例子是正确的.

It seems that in order to better illustrate the point an example would be in order.

下面的两个程序除了显示将程序逻辑封装到对象中以及使用静态函数的替代方案之间的区别外,还没有用.

The two programs below are pretty useless outside of their intended purpose of showing the differences between encapsulating your program logic into objects, and the alternative -using static functions.

该程序定义了两个运算,并且将对两个数字起作用(在示例中为10和25).程序运行时,它将把操作跟踪到一个日志文件(每个数字一个).可以想象可以用更严格的算法代替这两个操作,而可以用一系列更有用的输入数据代替这两个数字.

The program defines two operation and will work on two numbers (10 and 25 in the example). As the program runs, it will trace its' operations to a log file (one for each number). It is useful to imagine that the two operations could be replaced by more serious algorithms and that the two numbers could be replaced by a series of more useful input data.

//The instance-based version:
class Program
{
    private System.IO.StreamWriter _logStream;
    private int _originalNumber;
    private int _currentNumber;

    public Program(int number, string logFilePath)
    {
        _originalNumber = number;
        _currentNumber = number;
        try
        {                
            _logStream = new System.IO.StreamWriter(logFilePath, true);
            _logStream.WriteLine("Starting Program for {0}", _originalNumber);
        }
        catch
        {
            _logStream = null;
        }
    }
    public void Add(int operand)
    {
        if (_logStream != null)
            _logStream.WriteLine("For {0}: Adding {1} to {2}", _originalNumber, operand, _currentNumber);
        _currentNumber += operand;
    }
    public void Subtract(int operand)
    {
        if (_logStream != null)
            _logStream.WriteLine("For {0}: Subtracting {1} from {2}", _originalNumber, operand, _currentNumber);
        _currentNumber -= operand;            
    }
    public void Finish()
    {            
        Console.WriteLine("Program finished. {0} --> {1}", _originalNumber, _currentNumber);
        if (_logStream != null)
        {
            _logStream.WriteLine("Program finished. {0} --> {1}", _originalNumber, _currentNumber);
            _logStream.Close();
            _logStream = null;
        }
    }

    static void Main(string[] args)
    {
        Program p = new Program(10, "log-for-10.txt");
        Program q = new Program(25, "log-for-25.txt");

        p.Add(3);         // p._currentNumber = p._currentNumber + 3;
        p.Subtract(7);    // p._currentNumber = p._currentNumber - 7;
        q.Add(15);        // q._currentNumber = q._currentNumber + 15;
        q.Subtract(20);   // q._currentNumber = q._currentNumber - 20;
        q.Subtract(3);    // q._currentNumber = q._currentNumber - 3;

        p.Finish();       // display original number and final result for p
        q.Finish();       // display original number and final result for q
    }
}

以下是基于静态功能的同一程序的实现.请注意,我们必须如何将状态携带"到每个操作中以及从每个操作中携带出来",以及Main函数需要如何记住"哪个数据与哪个函数调用一起使用.

Following is the static functions based implementation of the same program. Notice how we have to "carry our state" into and out of each operation, and how the Main function needs to "remember" which data goes with which function call.

class Program
{
    private static int Add(int number, int operand, int originalNumber, System.IO.StreamWriter logFile)
    {
        if (logFile != null)
            logFile.WriteLine("For {0}: Adding {1} to {2}", originalNumber, operand, number);
        return (number + operand);
    }
    private static int Subtract(int number, int operand, int originalNumber, System.IO.StreamWriter logFile)
    {
        if (logFile != null)
            logFile.WriteLine("For {0}: Subtracting {1} from {2}", originalNumber, operand, number);
        return (number - operand);
    }
    private static void Finish(int number, int originalNumber, System.IO.StreamWriter logFile)
    {
        Console.WriteLine("Program finished. {0} --> {1}", originalNumber, number);
        if (logFile != null)
        {
            logFile.WriteLine("Program finished. {0} --> {1}", originalNumber, number);
            logFile.Close();
            logFile = null;
        }
    }

    static void Main(string[] args)
    {
        int pNumber = 10;
        int pCurrentNumber = 10;
        System.IO.StreamWriter pLogFile;
        int qNumber = 25;
        int qCurrentNumber = 25;
        System.IO.StreamWriter qLogFile;

        pLogFile = new System.IO.StreamWriter("log-for-10.txt", true);
        pLogFile.WriteLine("Starting Program for {0}", pNumber);
        qLogFile = new System.IO.StreamWriter("log-for-25.txt", true);
        qLogFile.WriteLine("Starting Program for {0}", qNumber);

        pCurrentNumber = Program.Add(pCurrentNumber, 3, pNumber, pLogFile);
        pCurrentNumber = Program.Subtract(pCurrentNumber, 7, pNumber, pLogFile);
        qCurrentNumber = Program.Add(qCurrentNumber, 15, qNumber, qLogFile);
        qCurrentNumber = Program.Subtract(qCurrentNumber, 20, qNumber, qLogFile);
        qCurrentNumber = Program.Subtract(qCurrentNumber, 3, qNumber, qLogFile);

        Program.Finish(pCurrentNumber, pNumber, pLogFile);
        Program.Finish(qCurrentNumber, qNumber, qLogFile);
    }
}

要注意的另一点是,尽管第一个基于实例的示例有效,但实际上将逻辑封装在不同的类中更为常见,该类可在程序的Main入口点中使用.这种方法更加灵活,因为它可以非常轻松地采用程序逻辑并将其移动到其他文件,甚至移动到甚至可以由多个应用程序使用的其他程序集.这是做到这一点的一种方法.

Another point to note is that although the first instance-based example works, it is more common in practice to encapsulate your logic in a different class which can be used in the Main entry point of your program. This approach is more flexible because it makes it very easy to take your program logic and move it to a different file, or even to a different assembly that could even be used by multiple applications. This is one way to do that.

// Another instance-based approach
class ProgramLogic
{
    private System.IO.StreamWriter _logStream;
    private int _originalNumber;
    private int _currentNumber;

    public ProgramLogic(int number, string logFilePath)
    {
        _originalNumber = number;
        _currentNumber = number;
        try
        {                
            _logStream = new System.IO.StreamWriter(logFilePath, true);
            _logStream.WriteLine("Starting Program for {0}", _originalNumber);
        }
        catch
        {
            _logStream = null;
        }
    }
    public void Add(int operand)
    {
        if (_logStream != null)
            _logStream.WriteLine("For {0}: Adding {1} to {2}", _originalNumber, operand, _currentNumber);
        _currentNumber += operand;
    }
    public void Subtract(int operand)
    {
        if (_logStream != null)
            _logStream.WriteLine("For {0}: Subtracting {1} from {2}", _originalNumber, operand, _currentNumber);
        _currentNumber -= operand;            
    }
    public void Finish()
    {            
        Console.WriteLine("Program finished. {0} --> {1}", _originalNumber, _currentNumber);
        if (_logStream != null)
        {
            _logStream.WriteLine("Program finished. {0} --> {1}", _originalNumber, _currentNumber);
            _logStream.Close();
            _logStream = null;
        }
    }        
}


class Program
{        
    static void Main(string[] args)
    {
        ProgramLogic p = new ProgramLogic(10, "log-for-10.txt");
        ProgramLogic q = new ProgramLogic(25, "log-for-25.txt");

        p.Add(3);         // p._number = p._number + 3;
        p.Subtract(7);    // p._number = p._number - 7;
        q.Add(15);        // q._number = q._number + 15;
        q.Subtract(20);   // q._number = q._number - 20;
        q.Subtract(3);    // q._number = q._number - 3;

        p.Finish();
        q.Finish();     
    }
}

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

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