我一直使用以下代码共享数据库变量:

Namespace DataAccessVariables
    Public Class Vars
        Public Shared s As String
        Public Shared con As String = WebConfigurationManager.ConnectionStrings("Dev").ToString()
        Public Shared c As New SqlConnection(con)
        Public Shared x As New SqlCommand(s, c)
    End Class
End Namespace

然后,我这样将其导入我的项目:

Imports DataAccessVariables.Vars

当我使用FXCOP检查网站时,我会收到此消息:

Error, Certainty 90, for StaticHolderTypesShouldNotHaveConstructors
{
    Target       : DBVars  (IntrospectionTargetType)
    Resolution   : "Remove the public constructors from 'Vars'."
    Help         : http://msdn2.microsoft.com/library/ms182169(VS.90).aspx  (String)
    Category     : Microsoft.Design  (String)
    CheckId      : CA1053  (String)
    RuleFile     : Design Rules  (String)
    Info         : "Instances of types that define only static members 
                   do not need to be created. Many compilers will automatically 
                   add a public default constructor if no constructor 
                   is specified. To prevent this, adding an empty private 
                   constructor may be required."
    Created      : 2010/04/20 01:25:16 PM  (DateTime)
    LastSeen     : 2010/04/21 07:17:46 AM  (DateTime)
    Status       : Active  (MessageStatus)
    Fix Category : Breaking  (FixCategories)
}

如果我从声明中删除了“公共共享”,则不会在我的页面中拾取变量。谁能告诉我正确的分享方式?

非常感谢,菲尔。

有帮助吗?

解决方案

此错误并没有告诉您删除公共共享变量。相反,它让您知道可以创建您的新实例 Vars 班级,即使它仅包括 Shared 成员。要解决该问题,请定义私人构造函数:

Private Sub New()
End Sub

这将阻止任何创建一个实例的代码 Vars 班级本身的课程。

其他提示

只要 您班上的代码?

另外,您不应创建全局(静态) SqlConnection. 。只需创建 SqlConnectionSqlCommand 对象按需。连接池将确保一次仅进行一个物理数据库连接。

您在这里获得的方式不是线程安全(例如,如果两个人同时提出请求,例如,事情将会得到 真的 螺旋)。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top