ReSharper complains when method can be static, but isn't

前端 未结 8 1354
萌比男神i
萌比男神i 2020-11-28 08:43

Why does ReSharper complain when a method can become static, but is not?

Is it because only one instance of a static method is created (on the type) and thus save on

8条回答
  •  难免孤独
    2020-11-28 08:51

    For me, the greatest benefit of this ReSharper advice (you can set it as a warning, suggestion, or hint). Is that it encourages me to make as many methods static as possible. This is a Good Thing, since a static method has no direct dependency on the class it is a member of. This means that it can easily be moved to another class as a static member.

    Another neat trick with statics in ReSharper is to make a set of related methods static by using the "Make Method Static" refactoring. This will move some of the dependencies into method parameters. When you look at this set of methods later, you may find they all access a particular object of a particular type. You can then use the "Make method non-static" refactoring, and specify that object as being the new this pointer. That moves your method into the other class.

    From this:

    internal class ClassA
    {
        public ClassB Property { get; set; }
    
        public int Method()
        {
            var classB = Property;
            return classB.Property1 + classB.Property2;
        }
    }
    
    internal class ClassB
    {
        public int Property1 { get; set; }
        public int Property2 { get; set; }
    }
    

    to this:

        public static int Method(ClassB property)
        {
            var classB = property;
            return classB.Property1 + classB.Property2;
        }
    

    to this:

    internal class ClassA
    {
        public ClassB Property { get; set; }
    }
    
    internal class ClassB
    {
        public int Property1 { get; set; }
        public int Property2 { get; set; }
    
        public int Method()
        {
            return Property1 + Property2;
        }
    }
    

提交回复
热议问题