[.NET]讓function回傳value的型態為動態dynamic(ex:可回傳string or double or.....)

  • 410
  • 0

[.NET]讓function回傳value的型態為動態dynamic(ex:可回傳string or double or.....)

像是下面這樣宣告function:

public dynamic GetHitData<T>(string myVar)
{
	string createTime = "";
	double score = 0;	
	
	if (typeof(T) == typeof(string))
	{                             
		return createTime;
	}
	else
	{
		return score.ToString();
	}
}


使用的時候,像是下面這樣使用,就可以回傳不同型態的value了,下面是用LINQ為範例,一般的程式碼當然也OK

var DataTableQuery = from pr in db.tblMyPRTable.AsEnumerable()
	 join hr in db.tblMyHRTable on pr.Idno equals hr.EMPLID
	 where (input.Locations == "0" ? true : hr.LOCATION == input.Locations)	 
	 select new AttendDTModel
	 {		 
		 ScoreIn = GetHitData<double>(pr.Idno),
		 ScoreOut = GetHitData<double>(pr.Idno),
		 HitInTime = GetHitData<string>(pr.Idno),		 
		 ClockInFlag = -1,
		 ClockOutFlag = -1,
		 ClockInName = "",
		 ClockOutName = ""
	 };