【发布时间】:2011-06-09 17:06:39
【问题描述】:
我做了一个这样的方法
class PersonCollection
{
[Contracts.CanReturnNull] //dont know if something like this exists?
IPerson GetPerson(Guid personId)
{
if (this.persons.Contains(personId))
return this.persons[personId];
else
return null;
}
}
现在调用代码需要正确处理空值。有没有办法为所有调用者表达他们需要能够处理此方法返回的空值的合同?
PersonCollection pc = new PersonCollection();
IPerson p = pc.GetPerson(anyId);
p.Name = "Hugo"; // here I want to have a curly line
我想要的是 p 被标记为潜在问题。
编辑 我只是修改了代码并添加了调用代码和预期的行为。我还添加了一个可能在 GetPerson 方法上不存在的属性
【问题讨论】:
-
在 C# 引用类型变量中,
null作为默认值。除非GetPerson通过合同确保IPerson不为空,否则调用者必须处理null返回的可能性。 -
我建议将方法名称更改为 GetPersonOrNull,如果您想让调用者清楚他可能会得到一个空值。
标签: c#-4.0 code-contracts design-by-contract