[英]Workaround for generics with static methods
我正在实现类似于NUnit的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);
}
我怎样才能最好地重构此类,以符合这两个规则?
我会问一个不同的问题:您为什么需要这样的方法?
Assert.PropertyHasValue(foo, "bar", true)
与Assert.AreEqual(foo.bar, true)
吗?
它的:
如果确实需要这样做,则可能需要使用Func<U, T>
而不是string
来指定属性:
public static class Assert
{
public static void PropertyHasValue<T,U>(T obj, Func<T, U> propertyGetter, U expectedValue)
{
var value = propertyGetter(obj);
Assert.AreEqual(expectedValue, value);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.