考虑以下层次结构:
public abstract class Base<T>
{
protected abstract T N { get; set; }
}
public abstract class Intermediate<T> : Base<T>
{
protected override T N { get; set; }
}
public class Derived : Intermediate<int>
{
public Derived() { N = 1; }
protected override sealed int N { get; set; }
}
运行Visual Studio 2015 Professional Code Analysis会生成警告
Warning CA2214 'Derived.Derived()' contains a call chain that results in a call to a virtual method defined by the class. Review the following call stack for unintended consequences:
Derived..ctor()
Base<T>.set_N(T):Void
这与another Stack Overflow question类似,但Derived
中的属性已被标记为sealed
。
另一方面,下面的代码,不使用任何泛型,不会产生任何警告:
public abstract class Base
{
protected abstract int N { get; set; }
}
public abstract class Intermediate : Base
{
protected override int N { get; set; }
}
public class Derived : Intermediate
{
public Derived() { N = 1; }
protected override sealed int N { get; set; }
}
同样,如果我跳过中间类而不是从Derived
派生Base
,警告就会消失,即使在通用情况下也是如此。另一方面,如果我删除后一个示例的sealed
修饰符,则会按预期重新显示警告。
那么,这是否适用于通用案例?如果是这样,那么应该小心的例子是什么?