派生类应该调用基类的静态方法,但具有重写的属性
我该怎么做?
场景:
abstract class DataAccess
{
public abstract string ConnectionString { get; set; }
public static DataTable ExecuteSql(string sql)
{
// ...
}
public static object ExecuteStoredProc(string storedProcName, ...)
{
// ...
}
}
abstract class DataAccessDb1 : DataAccess
{
public override string ConnectionString = "SetDbSpecificConnectionStringHere";
public static DataTable GetStuff()
{
// Call the method with the ConnectionString set HERE.
return ExecuteSql("select * from stuff");
}
}
我知道可以像在派生类中一样设置连接字符串,但我想将其保持静态,因此我不会在派生类中的每个方法中设置该属性...有什么想法吗?
How do I do that?
The scenario:
abstract class DataAccess
{
public abstract string ConnectionString { get; set; }
public static DataTable ExecuteSql(string sql)
{
// ...
}
public static object ExecuteStoredProc(string storedProcName, ...)
{
// ...
}
}
abstract class DataAccessDb1 : DataAccess
{
public override string ConnectionString = "SetDbSpecificConnectionStringHere";
public static DataTable GetStuff()
{
// Call the method with the ConnectionString set HERE.
return ExecuteSql("select * from stuff");
}
}
I know it's know possible to set the connection string like in the derived class, but I want to keep it static, therefore I won't set the property in every method in the derived class... Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是:将连接字符串作为参数传递到方法中。
DataAccessDb1
中的声明无效static
并且多态性不能混合所以基本上,如果您想要多态行为,则应该使用实例成员。如果您确实不需要多态行为,请将任何变体(例如连接字符串)作为该方法的参数传递。
Yes: pass the connection string in as a parameter into the method.
DataAccessDb1
is invalidstatic
and polymorphism don't mixSo basically, if you want polymorphic behaviour, you should be using instance members. If you don't really need polymorphic behaviour, pass any variations (such as the connection string) as a parameter for the method.
C# 中没有静态继承,因此让
ConnectionString
具有静态成员并覆盖它的目标将不起作用。重新考虑您的设计 - 将ConnectionString
设置为静态确实表示该字段在所有DataAccess
实例上应该相同,因为它是在类型本身上定义的。使用静态方法是否有特殊原因 - 使用实例方法并在构造函数中设置连接字符串会起作用:
There is no static inheritance in C# so your goal of having the
ConnectionString
has a static member and override it won't work. Rethink your design - havingConnectionString
as static really says this field should be the same on all yourDataAccess
instances since it is defined on the type itself.Is there a particular reason you use static methods - using instance methods and setting the connection string in the constructor would work:
我认为抽象类中应该只有一个 ExecuteSql 方法,并且所有派生类都将使用各自的连接字符串实现 ExecuteSql ,
可以从基类中删除。
What I think that you should only have a ExecuteSql method in the abstract class and all derived classes would implement ExecuteSql with their respective connection string,
can be removed from the base class.