Why following code does not work?
public void getData<T>(T ConnectionStirng)
{
OleDbConnection con = new OleDbConnection(connectionString); \\compile error
}
Because the connectionString
should be a string, not T
.
The OleDbConnection
class only has two constructors:
OleDbConnection() // Empty parameter list
and
OleDbConnection(string connectionString) // takes a connection string
When you compile by trying to pass in an object of type T, there's no way for the compiler to know what type that is (since it's not being used in context at that point).
Therefore, since T isn't guaranteed to be a string...there is no overload for the OleDbConnection that matches the parameters you're calling it with.
In this case, since there's no return value and the connectionString must be of type string...there's no need for generics at all. It can be simply written as:
public void getData(string connectionString)
Unless you're trying to return a collection of data of type T, then it would look like:
public IEnumerable<T> getData<T>(string connectionString)
Edit
...and none of that addresses the fact that your parameter name doesn't match what you're trying to pass to the constructor or the fact that the slashes in your comments are backwards.
Because OleDbConnection expects a string and you've passed a T.
Looking at the code you don't actually need generics. Surely this is enough:
public void getData(string connectionString)
{
OleDbConnection con = new OleDbConnection(connectionString);
}
Because OleDbConnection's constructor only takes a string.
精彩评论