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



>我经常使用

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;

PS:我首先补充了我如何试图克服这个问题(没有成功tbh),但后来我删除了它(我做了一个多小时的帖子!),因为它使问题太吵了。一开始可能看起来很容易,直到你(或者只有我?)试图解决它。我将其标记为dbml因为特定于DataContext事情:您不能使用单例等。

不幸的是,没有某种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>())

相关内容

  • 没有找到相关文章

最新更新