我有以下自定義NUnit限制。它會(當正確實施時)測試給定DateTime
等於明天。未強制執行泛型參數
public class TomorrowConstraint : Constraint
{
public TomorrowConstraint()
{
Description = "Tomorrow";
}
public override ConstraintResult ApplyTo<DateTime>(DateTime actual)
{
return new ConstraintResult(this, actual, true);
}
}
請注意,我給了Type參數一個具體類型,而不是泛型類型。
測試下面利用它:
[TestFixture]
public class X
{
[Test]
public void Foo()
{
Assert.That("string", new TomorrowConstraint());
}
}
我傳遞一個string
,不一個DateTime
,但該字符串傳遞給方法沒有任何問題。
如果我看看actual.GetType()
的類型,我可以看到它是一個字符串:{Name = "String" FullName = "System.String"}
。
這是怎麼發生的?
我以爲我會得到一個例外的地方異常?
你沒有制約的typeof'actual'到'DateTime',你只是命名通用參數應用於''DateTime'。如果你把它叫做'T',它會起到同樣的作用。如果您嘗試訪問'actual'上的任何'DateTime'成員(除了'object'定義的那些成員之外),您將得到一個類型錯誤。 – Lee