【问题标题】:Virtual member call in constructor, sealed, and attributes构造函数、密封和属性中的虚拟成员调用
【发布时间】:2014-09-13 12:12:09
【问题描述】:

我有以下结构:

public abstract class A
{
    public abstract string Foo {get;set;}
}

public class B : A
{ 
    public B() { Foo = "test" } //ReSharper: Virtual member call in constructor

    [Bar(1, 2)]
    public override string Foo {get;set;}
}

public class C : B
{
    [Bar(2,3)]
    public override string Foo {get;set}
}

如您所见,我收到 ReSharper 发出的关于在 Ctor 中进行虚拟成员调用的警告。所以我想:

  • 使 A.Foo 虚拟化
  • 使 B.Foo 覆盖密封

但后来我遇到了问题,我需要使用Bar 属性来装饰属性...

我不需要在C 中覆盖Foo,除了这个事实;那么有没有办法做到这一点?

【问题讨论】:

  • 您可以在 A 中创建一个带有支持字段的普通属性,并添加一个重载的构造函数,该构造函数设置该支持字段的值,也在 A 中,然后从 B 链接到该构造函数。这样任何构造函数中都不会有虚拟调用,您不必密封 B。

标签: c# inheritance overriding resharper custom-attributes


【解决方案1】:

如果您在 B 的构造函数中所做的只是为 Foo 设置默认值,只需使用带有支持字段的属性并在字段初始值设定项中设置默认值:

public class B : A
{
 private string foo = "test";

 [Bar(1, 2)]
 public override string Foo
 {
  get { return foo; }
  set { foo = value; }
 }
} 

【讨论】:

    猜你喜欢
    • 2010-09-12
    • 2019-05-06
    • 1970-01-01
    • 1970-01-01
    • 2010-10-02
    • 2015-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多