C# 属性不应继承

发布于 2024-10-10 06:01:53 字数 409 浏览 0 评论 0原文

由于属性在 C# 中不会继承(至少我不认为它们会继承) - 当 MyTestMethod 测试运行时,以下代码如何仍然显示 Hello 弹出窗口:

[TestClass]
public class BaseTestClass {
    [TestInitialize]
    public void Foo() {
        System.Windows.Forms.MessageBox.Show("Hello");
    }
}

[TestClass]
public class TestClass : BaseTestClass {
    [TestMethod]
    public void MyTestMethod() {
        Assert.IsTrue(true);
    }
}

Since attributes don't inherit in C# (at least I didn't think they did) - how does the following code still display the Hello popup when the MyTestMethod test is run:

[TestClass]
public class BaseTestClass {
    [TestInitialize]
    public void Foo() {
        System.Windows.Forms.MessageBox.Show("Hello");
    }
}

[TestClass]
public class TestClass : BaseTestClass {
    [TestMethod]
    public void MyTestMethod() {
        Assert.IsTrue(true);
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

诗笺 2024-10-17 06:01:53

默认情况下会继承属性,但可以禁用此功能 - 请参阅 AttributeUsage.Inherited

如果您使用 AttributeUsage 属性来修饰属性定义,则可以设置此属性:

[AttributeUsage(AttributeTargets.Class, Inherited = false)]
public class MyAttribute : Attribute
{
}

Attributes are inherited by default but this can be disabled - see AttributeUsage.Inherited

If you decorate the attribute definition with an AttributeUsage attribute, you can set this property:

[AttributeUsage(AttributeTargets.Class, Inherited = false)]
public class MyAttribute : Attribute
{
}
好倦 2024-10-17 06:01:53

如果不按原样工作,请将方法 Foo 虚拟并重写它,然后将 TestInitialize 放在 TestClass 重写方法中

 [TestClass]
  public class BaseTestClass
  {

    public virtual void Foo()
    {
      System.Windows.Forms.MessageBox.Show("Hello");
    }
  }

  [TestClass]
  public class TestClass : BaseTestClass
  {
     [TestInitialize]
    public override void Foo()
    {
      base.Foo();
    }

    [TestMethod]
    public void MyTestMethod()
    {
      Assert.IsTrue(true);
    }
  }

If not working as is make method Foo virtual and just override it, and put the TestInitialize at your TestClass override method

 [TestClass]
  public class BaseTestClass
  {

    public virtual void Foo()
    {
      System.Windows.Forms.MessageBox.Show("Hello");
    }
  }

  [TestClass]
  public class TestClass : BaseTestClass
  {
     [TestInitialize]
    public override void Foo()
    {
      base.Foo();
    }

    [TestMethod]
    public void MyTestMethod()
    {
      Assert.IsTrue(true);
    }
  }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文