If a virtual property or virtual method is defined in a class, and the virtual property or method is accessed in the constructor, VisualStudio does not give a warning and compiles without problems, but if the ReSharper plugin is installed, a warning is given: "Virtual members are accessed in the constructor ", then, why is this a security risk, and here's an example to illustrate:
using System;namespace virtualdemo{class Program {static void Main (string[] args) {var test = new Subclass (); Console.readkey (); }} class BaseClass {Protected virtual string Virtualproperty {get; set;} Public BaseClass () {var p = virtualproperty; Virtualmethod (); } protected virtual void Virtualmethod () {}} class Subclass:baseclass {private M Ockclass _mockclass; Public subclass () {_mockclass = new Mockclass (); } protected override string Virtualproperty {get {return _mockclass.mockproperty;} set {_mockclass.mockproperty = value;} } protected override void Virtualmethod () {var p = _mockclass.mockproperty; }} class Mockclass {public string Mockproperty {get; set;} }}
The example is simple because a null reference error occurred while constructing subclass
because the base class constructor was run before the subclass constructor, and a member class was initialized in the subclass constructor, but the subclass was not constructed when the base class constructor accessed the virtual member. So there was a null citation error. There are several ways to avoid this, you can construct the member class by the way the subclass field is initialized, this syntax sugar avoids the constructor's timing problem, and the second is a virtual initialize method that can be defined in the first step of the subclass constructor, where the subclass initializes the required dependency when inheriting the method.