我们的目的是生成一个字符串输出,该输出需要遵守一组特定的语法规则。我创建了一个对象模型,以便通过 C# 的强类型强制执行该语法,以防止生成无效输出的可能性。
我可以创建积极的测试,即有效的 C# 生成有效的输出。我无法做的是运行否定测试,即确保尝试生成无效输出会在编译时引发错误。
显式示例:
namespace Abstract
{
public interface FooType { }
public interface FooString : FooType { }
}
public interface Integer : Abstract.FooType { }
public interface SingleLine : Abstract.FooString { }
public interface MultiLine : Abstract.FooString { }
public class Bar<T>
where T : Abstract.FooType
{
public Bar(string s) {
// do stuff with s and T, where T is SingleLine or MultiLine
}
public Bar(int i) {
// do stuff with i and T, where T is Integer
}
}
public static class Foo
{
public static Bar<T> Bar<T>(int i) where T : Integer {
return new Bar<T>(i);
}
public static Bar<SingleLine> Bar(string s) {
return new Bar<SingleLine>(s);
}
public static Bar<T> Bar<T>(string s) where T : Abstract.FooString {
return new Bar<T>(s);
}
}
所有这些只是为了让我能做到:
Foo.Bar<SingleLine>("some string"); // ok
Foo.Bar("another string"); // ok
Foo.Bar<MultiLine>("more\nstrings"); // still ok
Foo.Bar<Integer>(24) // also ok
// How to test these lines for compilation failure?
Foo.Bar<Integer>("no good");
Foo.Bar<MultiLine>(-1);
万一这很重要,我正在使用 VS2012 Express for Desktop。