What is the gain from declaring a method as static

后端 未结 9 552
别跟我提以往
别跟我提以往 2020-12-07 10:35

I\'ve recently been looking through my warnings in Eclipse and come across this one:

\"static

9条回答
  •  独厮守ぢ
    2020-12-07 11:30

    The methods you can declare as static are the ones that don't require instantiation, such as

    public class MyClass
    {
        public static string InvertText(string text)
        {
            return text.Invert();
        }
    }
    

    Which you can then in return call out in any other class without instanciating that class.

    public class MyClassTwo
    {
        public void DoSomething()
        {
            var text = "hello world";
            Console.Write(MyClass.InvertText(text));
        }
    }
    

    ... But that's something you probably already know. It doesn't give you any real benefits per se, other than making it more clear that the method doesn't use any instance variables.

    In other words, you can most safely just turn it off completely. If you know you will never use a method in other classes (in which case it should just be private), you don't need it to be static at all.

提交回复
热议问题