我创建了一个存储对象并返回新存储对象id的SPROC。现在,我想要返回int而不是int?
public int Save(Contact contact)
{
int? id;
context.Save_And_SendBackID(contact.FirstName, contact.LastName, ref id);
//How do I return an int instead of an int?
}
感谢您的帮助。
我创建了一个存储对象并返回新存储对象id的SPROC。现在,我想要返回int而不是int?
public int Save(Contact contact)
{
int? id;
context.Save_And_SendBackID(contact.FirstName, contact.LastName, ref id);
//How do I return an int instead of an int?
}
return id.Value; // If you are sure "id" will never be null
或者return id ?? 0; // Returns 0 if id is null
return id.GetValueOrDefault(0); // Or whatever default value is wise to use...
if (! id.HasValue)
throw new Exception("Value not found"); // TODO: Use better exception type!
return id.Value;
return id.Value;
if (id.HasValue) return id.Value;
else return 0;
id ?? 0
"。 - Blorgbeardreturn id ?? 0;
:) - Nelson Rothermel??
方法只检查一次。要检查零次(并且仍然表现完全相同),您可以使用return id.GetValueOrDefault()
。 - Marc Gravellreturn id.HasValue ? id.Value : 0;
如果id不为null,则返回其值,否则返回0。
return id ?? 0;
有什么问题?它实现了完全相同的功能并且更加高效。 - Philippe Leybaert
id.Value
将抛出异常。在某些情况下,这可能是适当的,否则,请使用??
。 - Eric Mickelsen??
只能用于 Nullable<> 类型,还是普通的引用类型也可以使用? - Nelson Rothermelx ?? y
基本上是x!=null ? x : y
的简写形式。 - SWeko