If a virtual property or virtual method is defined in a class and the virtual property or method is accessed in the constructor, VisualStudio will not give a warning and compile There is no problem, but if the Resharper plug-in is installed, a warning will be given: "A virtual member is accessed in the constructor." So, why is this a security risk? Here is an example:
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 MockClass _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; } } }
This example is very simple. A null reference error occurred when constructing SubClass
because the base class constructor runs before the subclass constructor, and a member class is initialized in the subclass constructor, but the base class When the constructor accesses the virtual member, the subclass has not yet been constructed, so a null reference error occurs. There are many ways to avoid this situation. You can construct member classes by initializing subclass fields. This syntactic sugar can avoid the timing problem of the constructor. The second one is to define a virtual Initialize method in the subclass constructor. The first step is to call the subclass to initialize the required dependencies when inheriting this method.
The above is the detailed content of What's wrong with accessing virtual members in constructors in C#?. For more information, please follow other related articles on the PHP Chinese website!