2014-12-01 41 views
-2

我有一个项目在C#winforms中,与一个文件称为:PublicSettings.cs(此文件是在一个文件夹中称为:类),我有一个变量。使用变量从另一个文件.cs

现在,我想从同一个项目中的其他文件使用该变量。

PublicSettings.cs

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace LVSetup.Class 
{ 
    class PublicSettings 
    {   
     private string _ConnStr = "Connection"; 

     public string ConnStr 
     { 
      get 
      { 
       return this._ConnStr; 
      } 
      set 
      { 
       this._ConnStr = value; 
      } 
     } 
    } 
} 

我想在文件中使用的变量ConnStrfrmLogin.cs

frmLogin.cs

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using LVSetup.Class; 

namespace LVSetup 
{ 
    public partial class frmLogin : Form 
    { 
     public frmLogin() 
     { 
      InitializeComponent(); 
     } 

     private void btnEnter_Click(object sender, EventArgs e) 
     {    
      string a = PublicSettings.ConnStr; 
     } 
    } 
} 

但没有ConnStrPublicSettings,只是(Equals and ReferenceEquals)

这里有什么问题?

+0

问题是您试图从静态上下文中访问非静态变量 – DairyLea 2014-12-01 20:46:31

+0

此问题似乎是无关紧要的,因为它是关于核心c#语法的,可以通过仔细阅读文档和教程轻松解决。 – walther 2014-12-01 20:47:35

+2

@walther,这是一个伟大的downvote原因..不是一个很好的理由。 – paqogomez 2014-12-01 20:48:12

回答

5

您需要将此字段设置为静态,才能在不创建类实例的情况下访问它。或者创建并实例化。什么套房最好取决于你想申请这门课程的逻辑以及以后如何使用。

实例方法

private void btnEnter_Click(object sender, EventArgs e) 
{    
    var settings = new PublicSettings(); 
    string a = settings.ConnStr; 
} 

静态字段的方法

class PublicSettings 
    {   
     private static string _ConnStr = "Connection"; 

     public static string ConnStr 
     { 
      get 
      { 
       return _ConnStr; 
      } 
      set 
      { 
       _ConnStr = value; 
      } 
     } 
    } 
+1

无法在静态属性中访问“this” – DLeh 2014-12-01 20:48:34

+0

@DLeh我已更新我的答案 – 2014-12-01 20:50:14

1

对于一个连接字符串,我要么使用一个配置文件(的app.config),或使财产静态只读属性(因为在运行时通常没有理由更改连接字符串):

class PublicSettings 
{   
    public static string ConnStr 
    { 
     get 
     { 
      return "Connection"; 
     } 
    } 
}