Mar*_*ber 3 c# testing reflection unit-testing
我有以下推导:
interface IMyInterface
{
string myProperty {get;}
}
class abstract MyBaseClass : IMyInterface // Base class is defining myProperty as abstract
{
public abstract string myProperty {get;}
}
class Myclass : MyBaseClass // Base class is defining myProperty as abstract
{
public sealed override string myProperty
{
get { return "value"; }
}
}
Run Code Online (Sandbox Code Playgroud)
我希望能够检查一个类的成员是否被声明为密封.有点像:
PropertyInfo property = typeof(Myclass).GetProperty("myProperty")
bool isSealed = property.GetMethod.IsSealed; // IsSealed does not exist
Run Code Online (Sandbox Code Playgroud)
所有这一切的意义是能够运行测试,检查代码/项目的一致性.
以下测试失败:
PropertyInfo property = typeof(Myclass).GetProperty("myProperty")
Assert.IsFalse(property.GetMethod.IsVirtual);
Run Code Online (Sandbox Code Playgroud)
听起来你想断言一个方法不能被覆盖.在这种情况下,您需要IsFinal和IsVirtual属性的组合:
PropertyInfo property = typeof(Myclass).GetProperty("myProperty")
Assert.IsTrue(property.GetMethod.IsFinal || !property.GetMethod.IsVirtual);
Run Code Online (Sandbox Code Playgroud)
MSDN的一些注意事项:
要确定方法是否可以覆盖,仅检查是否
IsVirtual为真是不够的.对于可覆盖的方法,IsVirtual必须为true且IsFinal必须为false.例如,方法可能是非虚拟的,但它实现了一种接口方法.公共语言运行库要求实现接口成员的所有方法都必须标记为虚拟; 因此,编译器将方法标记为虚拟最终.因此,有些情况下方法被标记为虚拟但仍然不可覆盖.
| 归档时间: |
|
| 查看次数: |
511 次 |
| 最近记录: |