Bool 问题 - 改变值
大家早上好。
我使用以下方法来尝试返回布尔值:
public static bool GetShowCatSubProdStatus(string memberid, string username)
{
MyEnts showcatsubprodstatus = new MyEnts.PDC_VDSOREntities35();
var r = from p in showcatsubprodstatus.tblKeyAccountInfoes
where p.MemberID == memberid && p.UserName == username
select p.ShowCatSubProd;
return r.Any();
}
当我调用此方法并调试它时,结果是正确的。但是,当我在页面加载中运行此方法时,尽管方法结果返回正确的结果,但当我单步执行时,布尔值会发生变化!
bool showcatsubprodstatus = MyEnts.GetShowCatSubProdStatus(_memberid, _username);
if (showcatsubprodstatus != true)
{
panCatSubProd.Visible = false;
}
有人可以解释一下这里发生了什么以及我如何解决这个难题吗?!
PS:抱歉太厚了。
编辑 - 正确,将其范围缩小到变量。无论方法结果如何,它总是返回“true”?!?!
Morning all.
I have the following method that I use to to try and bring back a bool:
public static bool GetShowCatSubProdStatus(string memberid, string username)
{
MyEnts showcatsubprodstatus = new MyEnts.PDC_VDSOREntities35();
var r = from p in showcatsubprodstatus.tblKeyAccountInfoes
where p.MemberID == memberid && p.UserName == username
select p.ShowCatSubProd;
return r.Any();
}
When I call this method and debug it, the result is correct. However, when I run this method in a page load, although the method result returns the correct result, when I step through, the boolean value changes!
bool showcatsubprodstatus = MyEnts.GetShowCatSubProdStatus(_memberid, _username);
if (showcatsubprodstatus != true)
{
panCatSubProd.Visible = false;
}
Can someone explain what is going on here and how I can solve this puzzler?!
PS: Apologies for being thick.
EDIT - Right, narrowed it down to the variable. It is always return 'true' regardless of the method result?!?!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这段代码返回一个
IEnumerable
:通过调用
.Any()
,您可以询问 IEnumerable 中是否有任何项目。如果有则返回 true;这就是为什么你总是得到真实的回报,因为它总能找到一些东西。
解决方案
要么调用 .SingleOrDefault() 返回唯一的元素(如果有),要么返回该类型的默认值。
This piece of code returns an
IEnumerable<bool>
:By calling the
.Any()
you are asking it if there are any items in the IEnumerable. If there are you return true;That is why you always get true back, because it always finds something.
The solution
Either you go for calling .SingleOrDefault() which returns the only element there is (if there is one) or returns the default value of that type.