开发者

error in Generic [closed]

开发者 https://www.devze.com 2023-02-06 05:51 出处:网络
It's difficult to tell what is being asked here. This question is a开发者_C百科mbiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. Fo
It's difficult to tell what is being asked here. This question is a开发者_C百科mbiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 12 years ago.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消