gpt4 book ai didi

c# - 为构造函数参数设置契约

转载 作者:太空宇宙 更新时间:2023-11-03 13:06:35 25 4
gpt4 key购买 nike

假设我们有一个与合约类的接口(interface)如下

[ContractClassFor(typeof(Custom))]
public abstract class CustomContract : Custom
{
public string GetPerson(int i)
{
Contract.Requires(i > 0);
Contract.Ensures(!String.IsNullOrEmpty(Contract.Result<string>()));
return default(string);
}
public string Name { get; set; }
}

[ContractClass(typeof(CustomContract))]
public interface Custom
{
string GetPerson(int i);
string Name { get; set; }
}

实现就像

    public class CustomProcessor: Custom
{
public CustomProcessor(ISomeinterface obj, string logname)
{
if(null == obj) throw new ArgumentNullException(...);
...
}
public GetPerson(int I)
{
...
}
}

将构造函数中的 throw new ArgumentNullException 替换为 Contract.Requires(obj != null). 是否有意义?

契约应该由接口(interface)定义,因为构造函数是实现的一部分而不是接口(interface),所以我倾向于当前的方法。这是一个好的做法吗?

最佳答案

要充分利用代码契约,是的,将 ArgumentNullException 抛出替换为 Contract.Requires 是有意义的。

考虑到您使用的是接口(interface)和契约(Contract)类,这完全没问题。除了在构造函数本身之外,没有其他地方可以验证构造函数参数。

如果您使用 ArgumentNullException 方法,那么您将错过代码契约的静态检查和其他好处。

关于c# - 为构造函数参数设置契约,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30608414/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com