我正在实现类似于NUnit's Assert的自定义Assert类。使用静态方法的泛型的解决方法
我们有Sonar打开StyleCop规则,它抱怨说我应该总是使用泛型而不是object
。如果我将我的类更改为通用类,那么我陷入泛型类不能有静态方法的规则。
例如,考虑这个代码(我目前的方法非常简化的版本):
public class Assert
{
public static void PropertyHasValue(object obj, string propertyName, object expectedValue)
{
var value = obj.GetType().GetProperty(propertyName).GetValue(obj, null);
Assert.AreEqual(expectedValue, value);
}
}
有实例方法在断言类将没有任何意义,我opnion。一个通用的方法会强迫我做这样的事情(未经测试)想要使用的TestCase时:
[TestCase("someProperty", 10)]
[TestCase("anotherProperty", "someString")]
public void TestMethod(string propertyName, object expectedValue)
{
Assert.PropertyHasValue<object>(myObj, propertyName, expectedValue);
}
我怎么能最好的重构这个类同时遵守这些规则?
你能举例说明吗?你有没有考虑过扩展方法? –
类不一定是通用的。使该方法通用。 – MarcinJuraszek