【发布时间】:2016-02-22 09:26:18
【问题描述】:
我正在实现一个类似于NUnit's Assert 的自定义 Assert 类。
我们使用 StyleCop 规则打开了 Sonar,它抱怨我应该始终使用泛型而不是 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);
}
}
在我看来,在 Assert 类中包含实例方法没有任何意义。当想要使用 TestCases 时,通用方法会迫使我做这样的事情(未经测试):
[TestCase("someProperty", 10)]
[TestCase("anotherProperty", "someString")]
public void TestMethod(string propertyName, object expectedValue)
{
Assert.PropertyHasValue<object>(myObj, propertyName, expectedValue);
}
我怎样才能最好地重构这个类以符合这两个规则?
【问题讨论】:
-
你能用代码举例吗?你考虑过扩展方法吗?
-
类不必是通用的。改为使用通用方法。