如何“扩展”一个类,使其变量可以返回一个前缀的值为

问题描述:

首先抱歉混淆的标题,我可以找到确切的话来描述的情况。但它很容易通过一个例子来理解。如何“扩展”一个类,使其变量可以返回一个前缀的值为

我们必须保存表名作为目录这样的静态类:

public static class Tables 
    { 
      public const string Employees= "DBEmploy1"; 
      public const string Sales = "Sale1"; 
      (...etc) 
    } 

而在我们的代码中使用它们像这样:

string sql="select name, surname from " + Tables.Employees + " where code='1'" 

但有时我们需要的前缀数据库连接或其他前缀/后缀到表中。目前的解决办法是宣布第二表目录:

public static class CurrentDB1Prefix="[databasex].dbo." 

public static class Tables 
     { 
       public const string Employees= "DBEmploy1"; 
       public const string Sales = "Sale1"; 
       (...etc) 
     } 
public static class TablesP 
     { 
       public static readonly string Employees= CurrentDB1Prefix + Employees; 
       public static readonly string Sales = CurrentDB1Prefix + Sales; 
       (...etc) 
     } 

而且在我们的代码使用它们,如:

string sql="select name, surname from " + TablesP.Employees + " where code='1'" 

省力保持2表列表,我们愿做这样的事情:

public static class CurrentDB1Prefix="[databasex].dbo." 
public static class Tables 
{ 
        public const string Employees= "DBEmploy1"; 
        public const string Sales = "Sale1"; 
        (...etc) 
} 
public static class TablesP 
{ 
    //this would return the above Table class variables with the prefixes somehow 
    return CurrentDB1Prefix + Table.TableVariablex; 
} 

这怎么办?或者可以使用一些近似值?

请勿使用static,也不要使用const。通过将字段转换为属性来使值运行时变化。就像这样:

public class Tables 
{ 
    public string CurrentPrefix = ...; 
    public string Employees { get { return CurrentPrefix + "DBEmploy1" }; 
    //(...etc) 
} 
+0

重要的是,我们希望有2个选项,表得到没有前缀和TablesP表名与前缀(仅在第一个做mainteinance) – VSP

+0

@让他们ase69s什么阻止你这样做?创建第二个类TablesP,或者创建采用'bool applyPrefix'参数的属性方法。 – usr

+0

作为semiconstant(当前前缀只在程序启动时分配,并且以后没有更改)的东西,我想使用最轻量级的选项(如const),因此它不必在每次访问第二个类时计算它,而且我要确保第一个类中的每个变量都有第二个类中的对应元素(例如,如果您不使用其子元素,则使用抽象或接口来警告您) – VSP