【问题标题】:Should I use public methods or writeonly properties in my class?我应该在我的类中使用公共方法还是只写属性?
【发布时间】:2013-06-04 14:24:05
【问题描述】:

我有一个包含类的类库。该类负责在程序和数据库之间形成连接并为我提供连接字符串:

public class DBcon
{
    private string pass = "";
    private string dbName = "";
    OleDbConnection con = new OleDbConnection();

    public string setdbName
    {
        set { dbName = value; }
    }

    public string setpass
    {
        set { pass = value; }
    }

    public OleDbConnection getsetcon
    {
        set { createcon(); }
        get { return con; }
    }

    private void createcon()
    {
        PathFinder dbPath = new PathFinder();    // just another class 

        string DBPath = "";

        dbPath.dbFilesPath = "db";
        dbPath.setDBName = dbName;
        DBPath = dbPath.dbFilesPath;

        con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + DBPath + ";" +
        "Persist Security Info = False;Jet OLEDB:Database Password=" + pass + "";
    }
}

首先,我想使用公共方法,即。 createcon,以避免所有属性,但后来我读到这是一个不好的做法。 然后我决定使用只写属性,但它们也被认为是不好的做法。

谁能告诉我该怎么做才能使我的班级成为一个结构良好的班级。我使用只写属性,因为我不想返回字符串。我只想要 OledbConnection。

任何帮助都将不胜感激,即使它改变了类的结构。

【问题讨论】:

  • 你为什么要这个?
  • 为什么要拥有只写属性?
  • 所以我可以提供 dbName 和密码
  • 我想使用公共方法......但后来我读到这是一个不好的做法。 - 也许,它并不总是坏事。在这种情况下,我更喜欢 1 方法甚至更好的构造函数。防止丢失属性。
  • 为什么公共方法应该是一种不好的做法?

标签: c# class oop methods properties


【解决方案1】:
public class DBConnection
{
    private string pass = string.Empty;
    private string dbName = string.Empty;

    private OleDbConnection connection;

    public void DBConnection(string dbName, string pass)
    {
        this.dbName = dbName;
        this.pass = pass;

        this.Initialize();
    }

    public OleDbConnection Connection
    {
        get {return this.connection;}
    }

    private void Initialize()
    {
        //all the initialization
        var connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + DBPath + ";" +
        "Persist Security Info = False;Jet OLEDB:Database Password=" + pass + "";
        this.connection = new OleDbConnection(connString);
    }
}

附言不要使用字符串连接,而是使用appropriate string builder 作为连接路径。

【讨论】:

  • 所以有一个公共方法可以吗?
  • 你在哪里看到公共方法?只有构造函数。
  • 抱歉,为什么要使用字符串生成器?效率更高吗?
  • @WaqasAli:因为这个类开发人员专门用于在运行时构建语法正确的连接字符串。
  • 澄清一下 - Dmitry Martovoi 提供的链接是正确的 - 但它是 OleDbConnectionStringBuilder,而不是常规 StringBuilder。
猜你喜欢
  • 1970-01-01
  • 2013-08-11
  • 2013-10-15
  • 1970-01-01
  • 1970-01-01
  • 2010-11-19
  • 1970-01-01
  • 2011-01-31
相关资源
最近更新 更多