Virtual member call in a constructor

后端 未结 18 1915
[愿得一人]
[愿得一人] 2020-11-22 01:27

I\'m getting a warning from ReSharper about a call to a virtual member from my objects constructor.

Why would this be something not to do?

18条回答
  •  情深已故
    2020-11-22 02:07

    There are well-written answers above for why you wouldn't want to do that. Here's a counter-example where perhaps you would want to do that (translated into C# from Practical Object-Oriented Design in Ruby by Sandi Metz, p. 126).

    Note that GetDependency() isn't touching any instance variables. It would be static if static methods could be virtual.

    (To be fair, there are probably smarter ways of doing this via dependency injection containers or object initializers...)

    public class MyClass
    {
        private IDependency _myDependency;
    
        public MyClass(IDependency someValue = null)
        {
            _myDependency = someValue ?? GetDependency();
        }
    
        // If this were static, it could not be overridden
        // as static methods cannot be virtual in C#.
        protected virtual IDependency GetDependency() 
        {
            return new SomeDependency();
        }
    }
    
    public class MySubClass : MyClass
    {
        protected override IDependency GetDependency()
        {
            return new SomeOtherDependency();
        }
    }
    
    public interface IDependency  { }
    public class SomeDependency : IDependency { }
    public class SomeOtherDependency : IDependency { }
    

提交回复
热议问题