我正在使用 MS Code Contracts,并且在使用接口继承和 ContractClassFor 属性时遇到了障碍。
给定这些接口和合约类:
[ContractClass(typeof(IOneContract))]
interface IOne { }
[ContractClass(typeof(ITwoContract))]
interface ITwo : IOne { }
[ContractClassFor(typeof(IOne))]
abstract class IOneContract : IOne { }
[ContractClassFor(typeof(ITwo))]
abstract class ITwoContract : IOneContract, ITwo { }
假设 IOne 和 ITwo 是实质性接口。因此 IOneContract 中将包含大量代码用于必要的检查。
我不想为 IOne 接口重复 ITwoContract 中的所有内容。我只想为 ITwo 接口添加新合约。从一个合约类继承另一个合约类似乎是重用该代码的可能方法。但我收到以下错误:
EXEC : warning CC1066: Class 'ITwoContract' is annotated as being the contract for the interface 'ITwo' and cannot have an explicit base class other than System.Object.
这是代码合同中的限制还是我做错了?我们的项目中有很多接口继承,如果我不知道如何解决这个问题,这感觉就像代码契约的交易破坏者。
代替:
[ContractClassFor(typeof(ITwo))]
abstract class ITwoContract : IOneContract, ITwo { }
只需继承合约即可:
[ContractClassFor(typeof(ITwo))]
abstract class ITwoContract : ITwo { }
您只需要提供有关新方法的合同ITwo
。合同来自IOneContract
会自动继承,并且可以声明所有继承的IOne
方法是抽象的——事实上,你cannot提供合同IOne
on ITwoContract
,不然CC会抱怨的:)
例如,如果你有这个:
[ContractClass(typeof (IOneContract))]
interface IOne
{
int Thing { get; }
}
[ContractClass(typeof (ITwoContract))]
interface ITwo : IOne
{
int Thing2 { get; }
}
[ContractClassFor(typeof (IOne))]
abstract class IOneContract : IOne
{
public int Thing
{
get
{
Contract.Ensures(Contract.Result<int>() > 0);
return 0;
}
}
}
[ContractClassFor(typeof (ITwo))]
abstract class ITwoContract : ITwo
{
public int Thing2
{
get
{
Contract.Ensures(Contract.Result<int>() > 0);
return 0;
}
}
public abstract int Thing { get; }
}
然后这个实现将在两种方法上显示“未经证实的合同”,正如预期的那样:
class Two : ITwo
{
public int Thing
{
get { return 0; }
}
public int Thing2
{
get { return 0; }
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)