如何使用常量重构遗留代码

时间:2015-03-16 10:44:45

标签: c# inheritance const

我有一个类作为数据库中特定表的包装器。在这个类的构造函数中(我们称之为MyLookup),我们进行一些初始化(例如读取一些元数据)。现在我应该在数据库中创建第二个表,它或多或少是第一个表的副本。

class MyLookup {
    public const TABLE_NAME = "MYTABLE";
    private readonly ITable table;

    MyLookup() { 
        this.table = OpenTable(TABLE_NAME); 
        /* further init */
    }
}

问题是初始化代码或多与“base”-table相同。唯一的区别是它的实际名称。通常我只需更改常量TABLE_NAME即可成为可在我的派生表类中重写的虚拟属性。但是,const可以在遗留代码中使用,因此将其更改为属性也会导致更改其访问权限(实例而不是静态代码)。那么,我如何通过对TABLE_NAME进行最少的更改来使用不同的MyLookup调用基本初始化?

1 个答案:

答案 0 :(得分:1)

在所有评论之后,这里(希望是)零冲突方法:

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public class TableNameAttribute : Attribute
{
  public string TableName { get; set; }
}

public class BaseLookup<TSelfReferenceType>
{
  public static string TABLE_NAME
  {
    get 
    { 
      var attributes = typeof(TSelfReferenceType).GetCustomAttributes(typeof(TableNameAttribute), false); 
      if (attributes == null || attributes.Length == 0)
      {
        return null;
      }
      return ((TableNameAttribute)attributes[0]).TableName;
    }
  }
}

[TableName(TableName = "MyLookup")]
public class MyLookup : BaseLookup<MyLookup>
{
}

[TableName(TableName = "ChildLookup")]
public class ChildLookup : BaseLookup<ChildLookup>
{
}

// write out MyLookup
Console.Out.WriteLine(MyLookup.TABLE_NAME);
// write out ChildLookup
Console.Out.WriteLine(ChildLookup.TABLE_NAME);