开发者

C# Attributes Aren't Supposed to Inherit

开发者 https://www.devze.com 2023-02-02 11:30 出处:网络
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:

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 : BaseTest开发者_如何学CClass {
    [TestMethod]
    public void MyTestMethod() {
        Assert.IsTrue(true);
    }
}


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
{
}


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);
    }
  }
0

精彩评论

暂无评论...
验证码 换一张
取 消