我对 C# 语言比较陌生,但是在 Google 搜索和 Stack Overflow 的帮助下,我已经完成了许多应用程序,其中包括使用 Office、系统服务、进程、WMI、SQL、Linq 和 Active Directory。 ..
尽管在使这些应用程序正常运行方面取得了成功,但我仍然不确定 C# 语言中的许多事情,例如良好的代码实践和使用许多关键字等。
C#类;我知道我可以用它们做什么,我知道构造函数和析构函数、实例化和属性,但我不确定什么时候应该使用它们。到目前为止,我已经在不同方法中的 Form1.cs 文件中编写了所有代码。这些方法使用完全不同的 API 做一系列不同的事情。这显然意味着尝试维护该代码可能会变得相当困难,而且我发现在我的 Form1.cs中找到任何东西越来越令人沮丧。
我对你们的问题是我应该将我的代码分成不同的类吗?我试图将与 SqlConnection 和 SqlCommands 相关的内容拆分到一个单独的类中,但没有在我的 Form1.cs 中多次实例化同一个类,我看不出这更容易或有任何好处。
我一直在尝试拼凑一个新的应用程序,但这次将功能保留在它自己的类中,我希望有人可以告诉我我很愚蠢并且做错了,或者至少给我一些指导。
这个应用程序最终将从 App.Config 加载我的连接字符串,连接到 SQL 数据库并使用数据库中的多个表填充 DataSet。这绝不是功能性的,因为我无法理解整个 Classes 问题。
partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    string myConnectionString;
    private void Form1_Load(object sender, System.EventArgs e)
    {
        AppConfig cfg = new AppConfig();
        if (cfg.loadConfig())
        {
            myConnectionString = cfg.myConnectionString();
        }
        
        if (!String.IsNullOrEmpty(myConnectionString))
        {
            SQLConn SQL = new SQLConn();
            if (SQL.createConnection(myConnectionString))
            {
                MessageBox.Show("Connected!");
            }
        }
    }
}
class myDataSet
{
    DataSet DataSet()
    {
        DataSet ds = new DataSet();
        SQLConn sql = new SQLConn();
        
        return ds;
    }
    public void fillData()
    {
        try
        {
            SqlCommand sqlCmd = new SqlCommand("SELECT * FROM hardware");                
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
}
class SQLConn : IDisposable
{
    SqlConnection sqlConn;
    public bool createConnection(string myConnectionString)
    {
        sqlConn = new SqlConnection();
        sqlConn.ConnectionString = myConnectionString;
        try
        {
            sqlConn.Open();
            return true;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        return false;
    }
    public void Dispose()
    {
        if (sqlConn.State == ConnectionState.Open)
        {
            sqlConn.Close();
            sqlConn.Dispose();
        }
    }
}
class AppConfig
{
    Configuration cfg;
    public bool loadConfig()
    {
        try
        {
            cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (!File.Exists(cfg.FilePath))
            {
                MessageBox.Show("No configuration file");
            }
            return true;
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        return false;
    }
    public string myConnectionString()
    {
        string connectionString = ConfigurationManager.ConnectionStrings["IT_ProjectConnectionString"].ConnectionString;
        return connectionString;
    }
}