6
我試圖使用ContractClass
和ContractClassFor
來定義接口的代碼合同。當一切都在同一個程序集中時,它工作的很好,但是如果我將接口定義及其各自的契約類放入不同的程序集中,那麼具體的類實現將不再適用。當ContractFor在不同的程序集上時,C#代碼合同不起作用
例如,此代碼的工作:
namespace DummyProject
{
[ContractClass(typeof(AccountContracts))]
public interface IAccount
{
void Deposit(double amount);
}
[ContractClassFor(typeof(IAccount))]
internal abstract class AccountContracts : IAccount
{
void IAccount.Deposit(double amount)
{
Contract.Requires(amount >= 0);
}
}
internal class Account : IAccount
{
public void Deposit(double amount)
{
Console.WriteLine(amount);
}
}
class Program
{
static void Main(string[] args)
{
Account account = new Account();
// Contract.Requires will be checked below
account.Deposit(-1);
}
}
}
現在,如果我有以下內容的單獨的項目:(從與上述不同組件)
namespace SeparateAssembly
{
[ContractClass(typeof(SeparateAssemblyAccountContracts))]
public interface ISeparateAssemblyAccount
{
void Deposit(double amount);
}
[ContractClassFor(typeof(ISeparateAssemblyAccount))]
internal abstract class SeparateAssemblyAccountContracts
: ISeparateAssemblyAccount
{
void ISeparateAssemblyAccount.Deposit(double amount)
{
Contract.Requires(amount >= 0);
}
}
}
,然後在主項目如果我寫:
namespace DummyProject
{
internal class AccountFromSeparateAssembly
: ISeparateAssemblyAccount
{
public void Deposit(double amount)
{
Console.WriteLine(amount);
}
}
class Program
{
static void Main(string[] args)
{
ISeparateAssemblyAccount accountFromSeparateAssembly =
new AccountFromSeparateAssembly();
// Neither of the two statements below will work
// Contract.Requires will be ignored
accountFromSeparateAssembly.Deposit(-1);
((AccountFromSeparateAssembly)accountFromSeparateAssembly).Deposit(-1);
}
}
}
然後Contract.Requires
不再檢查在Deposit
方法。
對此有任何想法嗎?非常感謝!
而當你用'ISeparateAssemblyAccount accountFromSeparateAssembly = ...'替換'var accountFromSeparateAssembly = ...'? –
謝謝,但我試過了,它仍然無法正常工作。我編輯它以包含您的建議 – PadawanLondon