无法从用法推断方法的类型参数.尝试明确指定类型参数 [英] The type arguments for methods cannot be inferred from the usage. Try specifying the type arguments explicitly

查看:31
本文介绍了无法从用法推断方法的类型参数.尝试明确指定类型参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 TextChanged() 事件在文本框中从 SQL Server 填充自动完成文本.[WindowsForm, C#]

I am trying to populate Autocomplete text from SQL Server in textbox using TextChanged() event. [WindowsForm, C#]

我有一个部分类表单

TextChanged 事件:

private void textBoxFilterCName_TextChanged(object sender, EventArgs e)
    {
        DataTable dt = FillCustomerName(textBoxFilterCName.Text);
        List<string> listNames = CustomerName.ConvertDataTableToList(dt);
        textBoxFilterCName.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
        AutoCompleteStringCollection dataName = new AutoCompleteStringCollection();
        dataName.AddRange(listNames.ToArray());
        textBoxFilterCName.AutoCompleteCustomSource = dataName;
        textBoxFilterCName.AutoCompleteSource = AutoCompleteSource.CustomSource;
    }

当我调用这个方法 CustomerName.ConvertDataTableToList() 时出现这个错误.

I am getting this error when I call this method CustomerName.ConvertDataTableToList().

无法从用法推断方法CustomerName.ConvertDataTableToList(DataTable)"的类型参数.尝试明确指定类型参数.

FillCustomerName() 方法

public DataTable FillCustomerName(string cName)
    {
        DataTable dtName = new DataTable();
        List<string> listName = new List<string>();
        try
        {
            dbconnection.Open();
            string query = "SELECT [Name] FROM Customers WHERE Is_Active=1 AND Name like @CName + '%'";
            using (SqlCommand cmd = new SqlCommand(query, dbconnection))
            {
                cmd.Parameters.Add("CName", SqlDbType.VarChar).Value = cName;
                dtName.Load(cmd.ExecuteReader());
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Connection Error");
        }
        finally
        {
            dbconnection.Close();
        }
        return dtName;
    }

客户名称类:

public static class CustomerName
{
    private static T CreateItemFromRow<T>(DataRow row, IList<PropertyInfo> properties) where T : new()
    {
        T item = new T();
        foreach (var property in properties)
        {
            if (property.PropertyType == typeof(System.DayOfWeek))
            {
                DayOfWeek day = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), row[property.Name].ToString());
                property.SetValue(item, day, null);
            }
            else
            {
                property.SetValue(item, row[property.Name], null);
            }
        }
        return item;
    }
    public static List<T> ConvertDataTableToList<T>(this DataTable table) where T : new()
    {
        IList<PropertyInfo> properties = typeof(T).GetProperties().ToList();
        List<T> result = new List<T>();

        foreach (var row in table.Rows)
        {
            var item = CreateItemFromRow<T>((DataRow)row, properties);
            result.Add(item);
        }
        return result;            
    }
}

当我调试应用程序时执行查询并成功生成结果.但我无法将数据表结果加载为列表.

The query is executed and results are generated successfully when I debug the application. But I could not load the datatable results as list.

非常欢迎对这种转换提出可能的建议.

Possible suggestions for this conversion are most welcome.

推荐答案

所以您想将您的 DataTable 转换为特定类型的对象列表.对?

So you want to convert your DataTable to a list of objects of a certain type. Right?

泛型方法仅从参数推断泛型类型 T.由于您没有 T 类型的参数,因此您需要明确指定它.所以当你写下这一行时:

The generic method infers the generic type T from the parameters only. Since you have no parameters of type T then you need to explicitly specify it. So when you write this line:

List<string> listNames = CustomerName.ConvertDataTableToList(dt);

编译器无法推断您想要的 T 类型是 string,因为它仅用于返回类型.所以你需要明确指定:

The Compiler can't infer what that the type T you want is a string because it is only used in the return type. So you need to explicitly specify that:

CustomerName.ConvertDataTableToList<string>(dt);

然而,由于您指定了条件 where T : new(),这意味着泛型类型应该有一个无参数的构造函数,string 不满足这一点.您正在按名称匹配行,因此您唯一的选择是修改通用方法或创建这样的类:

However, since you specify the condition where T : new(), this means the generic type should have a parameterless constructor, string doesn't satisfy that. You're matching the row by name, so your only option is to modify the generic methods or create a class like this:

public class CustomerNameHolder
{
    public string Name { set; get; }
}

那么:

List<string> listNames = CustomerName.ConvertDataTableToList<CustomerNameHolder>(dt)
                                     .Select(x=> x.Name).ToList();

这篇关于无法从用法推断方法的类型参数.尝试明确指定类型参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆