如何使用列表< T>在C#中 [英] How to use list<T> in C#

查看:91
本文介绍了如何使用列表< T>在C#中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如下:



as follow :

as Follow : 

          public List<T> GetDataReader<T>(string Command, int Cap)
             {
            SqlConnection con = this.openConnection();
            List<T> arr = new List<T>(Cap);
            object[] values = null;
            int fieldCount = 0;
            try
            {
                using (SqlCommand comm = new SqlCommand())
                {
                    comm.Connection = con;
                    comm.CommandText = Command;
                    comm.CommandType = CommandType.Text;
                    using (var reader = comm.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            values = new object[reader.FieldCount];
                            fieldCount = reader.GetValues(values);
                            for (int i = 0; i < fieldCount; i++)
                            {
                              
                                if(values[i] != System.DBNull.Value)
                                arr.Add((T)values[i]);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return arr;
        }


when Call the Method as below : 

      List<string>() = MyClass.GetDataReader<string>("select * from dbo.Users", 50);

i faced Syntax Error??!!





我尝试过:



我将被调用的方法更改为任何类型,但面临错误



What I have tried:

I changed called method to any typed , but faced Error

推荐答案

您的语法错误很明显:

Your syntax error is obvious:
List<string>() = MyClass...

您需要命名变量,并删除括号:

You need to name the variable, and get rid of the brackets:

List<string> myList = MyClass...



但是......正如debasish建议的那样,将SQL命令作为文本传递是非常危险的:如果你不是,它会让你暴露于SQL注入非常非常小心 - 这可以删除你的数据库!


But... as debasish suggested, passing an SQL command as text is very dangerous: it exposes you to SQL Injection if you aren't very, very careful - and that can delete your database!


这篇关于如何使用列表&lt; T&gt;在C#中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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