ฉันกำลังพยายามเขียนวิธีการตรวจสอบ เช่น สำหรับ double ดูเหมือนว่านี้:
protected bool ValidateLoopAttributes(string i_value, double i_threshold)
{
double result;
if (!(double.TryParse(i_value, out result) && result >= i_threshold))
{
return false;
}
return true;
}
เป็นไปได้ไหมที่จะเขียนสิ่งนี้เป็น:
protected bool ValidateLoopAttributes<T>(string i_value, T i_threshold)
แล้วใช้บางอย่างเช่น
T.GetType().TryParse() // how can i use here the type's methods??
การใช้คำสั่ง switch/if เป็นวิธีเดียวที่จะทำสิ่งนี้หรือไม่? เช่น:
If (T.GetType() is int)
Int32.TryParse(i_threshold)
มีวิธีที่สง่างามกว่านี้ไหม?
GetType()
เป็นวิธีการแบบอินสแตนซ์ ดังนั้นT.GetType()
จึงไม่ควรคอมไพล์ด้วยซ้ำ คุณต้องใช้typeof(T)
- person Cristian Lupascu   schedule 13.04.2012ValidateLoopAttributes(string i_value, double i_threshold)
และValidateLoopAttributes(string i_value, int i_threshold)
(หรือlong
) - person Rawling   schedule 13.04.2012