各位高手大家好
不好意思我C#環境不成熟,想問大家遇到這樣錯誤該怎麼處理
public List<employee> GetEmployee()
{
using (Data db = new Data(System.Configuration.ConfigurationManager.AppSettings["Text"]))
{
List<employee> list = new List<employee>();
var q = from p in db.employee
select p;
list = q.ToList();
List<NEWDATA> list2 = new List<NEWDATA>();
for (int i = 0; i < list.Count; i++)
{
NEWDATA emp = new NEWDATA();
epm.id = list[i].id;
emp.name = list[i].name;
emp.birth= Convert.ToDateTime(list[i].birth).ToString("yyyy/MM/dd");
list2.Add(emp);
return list_2;
}
}
}
class NEWDATA
{
public int id { get; set; }
public string name { get; set; }
public string birth { get; set; }
}
這個不用這麼麻煩
List<employee> list = new List<employee>();
var q = from p in db.employee
select p;
list = q.ToList();
改這樣就好
var list = (from p in db.employee
select p).ToList<employee>();
就不會出現型態不一的問題
不要用for 避免無回傳值的問題,個人建議用foreach
if(list.Any()){
foreach(var item in list){
NEWDATA emp = new NEWDATA();
epm.id = item.id;
emp.name = item.name;
emp.birth= Convert.ToDateTime(item.birth).ToString("yyyy/MM/dd");
list2.Add(emp);
// 不要在 for或foreach裡用return
}
}
自尋苦惱....寫太多會頭痛吧
public List<employee> GetEmployee(){
Data db = new Data(System.Configuration.ConfigurationManager.AppSettings["Text"]);
return ( from p in db.employee
select new NEWDATA{
id = p.id,
name = p.name,
birth = Convert.ToDateTime(p.birth).ToString("yyyy/MM/dd")
}};
}
真的不要寫一堆for又開一堆NEWDATA的LIST,這樣就好了
針對不是所有程式碼路徑都有回傳值........
不要只在 if(){ ... } 放 return
或者不要在if for while .......這類程式流程裡放return
如
public string GetPass()
{
string ret = "";
using (passForm apf = new passForm())
{
if (apf.ShowDialog() == DialogResult.OK)
{
ret = textBox1.Text.Trim();
}
}
return ret;
}
如果你把return 放進if或using裡,就會編譯錯誤
好的謝謝高手回應!因為和原本的方法比較不一樣,目前還在測試中,成功了再回覆您!
謝謝您細心詳細的解釋,最後成功了!
你可能要先想想為什麼要這樣做
看起來你已經定義GetEmployee這個方法的型別是employee
那為啥裡面還要有個NEWDATA這個型別?
然後沒有回傳值
public List<employee> GetEmployee()
{
using (Data db = new Data(System.Configuration.ConfigurationManager.AppSettings["Text"]))
{
List<employee> list = new List<employee>();
var q = from p in db.employee
select p;
list = q.ToList();
return list;
}
}
這樣應該暫時沒問題吧
之前問的問題
如果解決了
就去選最佳解答
public List<employee> GetEmployee()//回傳 List<employee> 與 list2(List<NEWDATA>)型態不符合,看你要改那一個
{
using (Data db = new Data(System.Configuration.ConfigurationManager.AppSettings["Text"]))
{
List<employee> list = new List<employee>();
var q = from p in db.employee
select p;
list = q.ToList();
List<NEWDATA> list2 = new List<NEWDATA>();
for (int i = 0; i < list.Count; i++)
{
NEWDATA emp = new NEWDATA();
epm.id = list[i].id;
emp.name = list[i].name;
emp.birth= Convert.ToDateTime(list[i].birth).ToString("yyyy/MM/dd");
list2.Add(emp);
}
return list2;//搬到迴圈外面,名稱改為 list2 (沒底線)
}
}