我正在尝试使用ContractClass和定义接口的代码合同ContractClassFor.当一切都在同一个程序集中时,它工作正常,但是如果我将接口定义及其各自的契约类放在不同的程序集中,那么具体的类实现,它就不再起作用了.
例如,此代码有效:
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在,如果我有一个单独的项目,具有以下内容:
namespace SeparateAssembly
{
[ContractClass(typeof(SeparateAssemblyAccountContracts))]
public interface ISeparateAssemblyAccount …Run Code Online (Sandbox Code Playgroud)