"return db.SaveChangesAsync()" 和 "return 0" 之间的区别
Different between "return db.SaveChangesAsync()" and "return 0"
我想在将新消息附加到数据库后获得状态。我定义了一个枚举(类型 int
),但是当我调用 return await db.SaveChangesAsync();
时该方法给了我 2 条错误消息
Cannot implicitly convert type 'xxx.Models.MessageStatus' to 'int'.
和
Cannot implicitly convert type 'int' to 'xxx.Models.MessageStatus'.
我的测试代码:
enum MessageStatus
{
Success,
Failure
}
private async Task<MessageStatus> AddMessage()
{
using (var db = new VinaChanelDbContext())
{
try
{
//do stuff...
await db.SaveChangesAsync();
return MessageStatus.Success; /* or return 0; */
}
catch { return 1; /* or return MessageStatus.Failure; */ }
}
}
MSDN doc 说:
SaveChangesAsync() will return Task<int>
所以,我的问题是:为什么 AddMessage
方法不接受
/* implicit conversion to MessageStatus.Success or MessageStatus.Failure */
return await db.SaveChangesAsync();
MessageStatus
和 int
:
之间没有隐式转换
Each enum type defines a distinct type; an explicit enumeration conversion (§6.2.2) is required to convert between an enum type and an integral type, or between two enum types.
from C# spec - 14.5 Enum values and operations
因此,您不能直接从定义为 return MessageStatus
的方法 return int
。出于同样的原因,您不能从声明为 return Task<MessageStatus>
.
的方法 return Task<int>
您可以在 return 之前将 int
转换为 MessageStatus
,但不能直接 return。
return (MessageStatus)(await db.SaveChangesAsync());
但是,这可能不是一个好主意,因为您不知道 int
值将 SaveChangesAsync
return,并且您的枚举可能与它不完全匹配。
我想在将新消息附加到数据库后获得状态。我定义了一个枚举(类型 int
),但是当我调用 return await db.SaveChangesAsync();
Cannot implicitly convert type 'xxx.Models.MessageStatus' to 'int'.
和
Cannot implicitly convert type 'int' to 'xxx.Models.MessageStatus'.
我的测试代码:
enum MessageStatus
{
Success,
Failure
}
private async Task<MessageStatus> AddMessage()
{
using (var db = new VinaChanelDbContext())
{
try
{
//do stuff...
await db.SaveChangesAsync();
return MessageStatus.Success; /* or return 0; */
}
catch { return 1; /* or return MessageStatus.Failure; */ }
}
}
MSDN doc 说:
SaveChangesAsync() will return
Task<int>
所以,我的问题是:为什么 AddMessage
方法不接受
/* implicit conversion to MessageStatus.Success or MessageStatus.Failure */
return await db.SaveChangesAsync();
MessageStatus
和 int
:
Each enum type defines a distinct type; an explicit enumeration conversion (§6.2.2) is required to convert between an enum type and an integral type, or between two enum types.
from C# spec - 14.5 Enum values and operations
因此,您不能直接从定义为 return MessageStatus
的方法 return int
。出于同样的原因,您不能从声明为 return Task<MessageStatus>
.
Task<int>
您可以在 return 之前将 int
转换为 MessageStatus
,但不能直接 return。
return (MessageStatus)(await db.SaveChangesAsync());
但是,这可能不是一个好主意,因为您不知道 int
值将 SaveChangesAsync
return,并且您的枚举可能与它不完全匹配。