C# 属性不应继承
由于属性在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
默认情况下会继承属性,但可以禁用此功能 - 请参阅 AttributeUsage.Inherited
如果您使用 AttributeUsage 属性来修饰属性定义,则可以设置此属性:
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:如果不按原样工作,请将方法 Foo 虚拟并重写它,然后将 TestInitialize 放在 TestClass 重写方法中
If not working as is make method Foo virtual and just override it, and put the TestInitialize at your TestClass override method