我创建了一个保存对象的SPROC并返回保存的新对象的id.现在,我想返回一个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?
}
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助
Phi*_*ert 16
return id.Value; // If you are sure "id" will never be null
Run Code Online (Sandbox Code Playgroud)
要么
return id ?? 0; // Returns 0 if id is null
Run Code Online (Sandbox Code Playgroud)
你可以GetValueOrDefault()在Nullable上使用这个功能.
return id.GetValueOrDefault(0); // Or whatever default value is wise to use...
Run Code Online (Sandbox Code Playgroud)
请注意,这类似于Richard77的合并答案,但我会说更具可读性......
但是,决定这是否是一个好主意取决于你.那么也许一个例外更合适?
if (! id.HasValue)
throw new Exception("Value not found"); // TODO: Use better exception type!
return id.Value;
Run Code Online (Sandbox Code Playgroud)