我有一个操纵几个数据库的项目。
我想实现的目标是让每个数据库 class ,其中将包含返回其表名称同时更新持有初始目录的全局变量。这是一个例子:
//What the class ideally would look like
class DB1
{
public const string Table1 = "schema.NameOfTable1"
public const string Table2 = "schema.NameOfTable2"
}
//Usage
string table_name = DB1.Table1 //This is the code which I'd like to leave unchanged
到目前为止很好,但是我也需要更新CS的初始目录。
可以使用属性代替
来实现class DB1
{
public static string Table1
{
get
{
SQLClass.InitialCatalogVariable = "NameOfDB1";
return "schema.NameOfTable1";
}
}
}
但是,这意味着我必须为每个表实现此代码。
我当然可以在db1构造函数中设置initialcatalog变量,但是随后我将被迫像 DB1 db = new DB1(); string table_name = db.Table1
一样实例化以执行构造函数代码,我想避免使用。
我想知道是否有另一种方法?欢迎任何建议
最后,我去了一个静态构造函数,每当将静态成员调用时,它将被触发。信用归功于用户@InBetween,由于某种原因删除了他的答案
class DB1
{
public static readonly string Table1 = "schema.NameOfTable1"
public static readonly string Table2 = "schema.NameOfTable2"
static DB1() { SQL.sInitialCatalog = "NameOfDB1"; }
}
string table_name = DB1.Table1; //Retrieves table name and updates InitialCatalog