0

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

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)
}

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

非常感谢,菲尔。

4

2 回答 2

5

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

Private Sub New()
End Sub

Vars这将防止任何代码在类本身之外创建类的实例。

于 2010-04-21T07:42:44.473 回答
4

这是你班上唯一的代码吗?

此外,您不应该创建全局(静态)SqlConnection。只需按需创建SqlConnection和对象。SqlCommand连接池将确保一次只建立一个物理数据库连接。

你在这里得到它的方式,它不是线程安全的(例如,如果两个人同时提出请求,事情会变得非常棘手)。

于 2010-04-21T07:45:20.067 回答