C# 从打开的DataReader中返回新对象-是否确定?
我看到了这个代码:C# 从打开的DataReader中返回新对象-是否确定?,c#,.net,datareader,C#,.net,Datareader,我看到了这个代码: public static ConsTypeCategory GetConsCategory(int providerId, int categoryId) { const string select = @"SELECT CategoryId, CategoryName, ExpectedDurationMins FROM constypecategories WHERE ProviderId = @Pro
public static ConsTypeCategory GetConsCategory(int providerId, int categoryId) {
const string select =
@"SELECT CategoryId, CategoryName, ExpectedDurationMins
FROM constypecategories
WHERE ProviderId = @ProviderId
AND CategoryId = @CategoryId
LIMIT 1";
MySqlParameter[] mySqlParameters = {
new MySqlParameter("ProviderId", providerId),
new MySqlParameter("CategoryId", categoryId)
};
using (MySqlDataReader dr = MySqlHelper.ExecuteReader(DB.ConnectionString, select, mySqlParameters)) {
while (dr.Read()) {
return new ConsTypeCategory(
dr.GetInt32("CategoryId"),
dr.GetString("CategoryName"),
dr.GetInt32("ExpectedDurationMins")
);
}
}
return null;
}
…并立即认为从datareader循环中返回“新”对象是错误的。但我试图为这种观点找到理由,结果却一无所获
是否有充分的理由不从“while”内返回?这没有什么错。您甚至可以在迭代器方法中使用它,并使用
yield return…
逐个返回对象。当它超出范围时,阅读器就会关闭。在这种情况下,在返回后
。在迭代器中,迭代停止后,您可以用if替换while。在这种情况下,您可能会感觉更好,因为您使用的是while
循环,但返回的是第一条记录。这表明你可能需要读更多的书。虽然它在功能上等同于使用if
,但您应该使用if
来明确表示您只希望它返回一个。同意@madreflection。下一个查看您的代码的开发人员将怀疑是否存在bug。“while”到“if”切换是有意义的。感谢大家的教育,特别是@PanagiotisKanavos对读者行为的澄清——我认为这是我“虚构”关注的领域!