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);
}
}
}
이제 다음과 같은 별도의 프로젝트가있는 경우 :
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
메서드 에서 확인되지 않습니다 .
이것에 대한 아이디어가 있습니까? 감사합니다!
및을 포함하는 프로젝트의 코드 계약 설정에서 Contract Reference Assembly
= Build
를 선택하여 작동하도록 관리했습니다 .ISeparateAssemblyAccount
SeparateAssemblyAccountContracts
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다