Derived class should call static methods of base class but with overriden property
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?
Yes: pass the connection string in as a parameter into the method.
- Fields don't behave polymorphically, so the declaration in
DataAccessDb1
is invalid static
and polymorphism don't mix
So 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.
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 - having ConnectionString
as static really says this field should be the same on all your DataAccess
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:
public class DataAccessDb1
{
public string ConnectionString {get;set;}
public DataAccessDb1()
{
ConnectionString = "SetDbSpecificConnectionStringHere";
}
public void DataTable GetStuff()
{
return DataAccess.ExecuteSql(ConnectionString, "select * from stuff");
}
}
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,
public abstarct string ConnectionString{get;set;}
can be removed from the base class.
精彩评论