使用基类中的继承成员(将可重复代码移动到基类中)

时间:2014-12-04 17:23:30

标签: c# architecture dbml

我经常使用

using (var context = new SomeDataContext(SomeDataContext.ConnectionString))
{
   ...
}

,其中

abstract class DataContextBase: DataContext { ... }

partial class SomeDataContext: DataContextBase
{
    public const string DatabaseFile = "blablabla.mdf";
    public static readonly string ConnectionString = string.Format(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename={0};Integrated Security=True", DatabaseFile);
}

问题:是否可以隐藏创建SomeDataContext个实例并ConnectionString深入DataContextBase

我想只在继承的类中定义文件名

partial class SomeDataContext: DataContextBase
{
    public const string DatabaseFile = "blablabla.mdf";
}

并且能够创建这样的实例

var context = SomeDataContext.PropertyInBaseClassWhichCreatesInstanceOfInheritedClass;

P.S。:我首先添加了我如何尝试克服这个问题(没有成功),但后来我删除了它(我这个帖子已经过了一小时!),因为它让问题太吵了。一开始看起来很容易,直到你(或者只是我?)试着解决它。我将其标记为dbml,因为具体针对DataContext事:您不能使用单身等等。

1 个答案:

答案 0 :(得分:1)

不幸的是,there isn't some sort of virtual static,如果您致电SomeDataContext.StaticPropertyInBaseClass,则会将其编译为DataContextBase.StaticPropertyInBaseClass。我认为你能做的最好就是这样:

// upside: simple SomeDataContext.Instance for external users
// downside: more code in SomeDataContext
partial class SomeDataContext : DataContextBase
{
    private const string DatabaseFile = "blablabla.mdf";
    public static SomeDataContext Instance
    {
        get
        {
            return new SomeDataContext(GetConnectionString(DatabaseFile));
        }
    }
}
abstract class DataContextBase
{
    protected static string GetConnectionString(string databaseFile)
    {
        return string.Format(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename={0};Integrated Security=True", databaseFile);
    }
}
// e.g. using (var context = SomeDataContext.Instance)

或者

// upside: just one line in child class
// downside: a little harder for external callers, with a little less type safety
// downside: as written, requires child class to have parameterless constructor
partial class SomeDataContext : DataContextBase
{
    protected override string DatabaseFileInternal { get { return "blablabla.mdf"; } }
}
abstract class DataContextBase
{
    protected abstract string DatabaseFileInternal { get; }
    private string ConnectionString
    {
        get
        {
            return string.Format(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename={0};Integrated Security=True", DatabaseFileInternal);
        }
    }
    public static T GetInstance<T>() where T : DataContextBase, new()
    {
        using (var tInst = new T())
            return (T)Activator.CreateInstance(typeof(T), tInst.ConnectionString);
    }
}
// e.g. using (var context = DataContextBase.GetInstance<SomeDataContext>())