问题描述
手动管理数据库连接时,您总是打开和关闭它。有时你需要检查连接是否有一些状态之前做一些动作。
经典情况是在关闭连接之前检查非Closed状态。
类似
When you manage database connection manually you always open and close it. Sometimes you need to check if connection has some state before do some action.A classic situation is check for not Closed state before close connection.Something like
if (connection.State != ConnectionState.Closed)
connnection.Close();
由于说明ConnectionState枚举WITH FLAGS。这意味着连接状态可以同时具有不同的状态。可能是Broken + Closed或其他...
As MSDN states the ConnectionState is enum WITH FLAGS. It means that connection state can have different states at same time. May be Broken+Closed or something else...
如果反编译System.Data.ConnectionState枚举,您将看到
If you decompile System.Data.ConnectionState enum you will see
[Flags]
public enum ConnectionState
{
Closed = 0,
Open = 1,
Connecting = 2,
Executing = 4,
Fetching = 8,
Broken = 16,
}
Closed项目的值为ZERO。这意味着以下是始终是真的:
The value of Closed item is ZERO. It means that following is always true:
connection.State.HasFlag(ConnectionState.Closed)
所以。任何建议为什么这个枚举有Flags属性?或者(如果这个枚举必须是Flags)为什么Closed项目有0值?
So. Any suggestions why does this enum have Flags attribute? Or (if this enum must be Flags) why does Closed item have 0 value?
推荐答案
实现他们计划做一个基于标志的枚举,但我不认为这是当前的实现如何使用,如果你看看中的库/ system.data.connectionstate(v = vs.110).aspx#Anchor_2rel =nofollow>
I believe in the original .NET 1.1 implementation they planed on making it a flags based enum, However I don't think that is how the current implementation is used if you look at the note in the remarks section
您不需要检查标志,可以安全地执行直接的 ==
测试。他们没有删除 Flags
属性,因为它会破坏它们不能做的.NET 1.1的二进制兼容性。
You don't need to check for flags it is safe to do a direct ==
test. They did not remove the Flags
attribute because it would break binary compatibility with .NET 1.1 which they won't do.
这篇关于.NET数据库连接的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!