2012-07-13 71 views
0

我試圖使用下面的代碼獲取字符串的ToLower()方法。如何從DateTime獲取ToString()

var tolowerMethod = typeof(string).GetMethods().Where(m => m.Name == "ToLower").FirstOrDefault(); 

我想獲取DateTime的ToString()方法。我已使用以下代碼

var formatMethod = typeof(DateTime).GetMethods().Where(m => m.Name == "ToString").ElementAt(1); 

這不是唯一的。我嘗試了下面的東西,但沒有成功。

var formatMethod2 = typeof(DateTime).GetMethods().Where(m => m.Name == "ToString").Where(x=>x.GetParameters().Select(t=>t.ParameterType).Equals(typeof(string))).FirstOrDefault(); 

任何想法?

謝謝

+0

DateTime類有'ToString()'方法的重載,那麼如何使用你的lin函數獲得單一方法q聲明。 – 2012-07-13 09:56:41

+0

哪個'ToString()'重載? – Bazzz 2012-07-13 10:01:53

回答

2

是否必須是linq? 你可能想是這樣的:

var x = typeof(DateTime).GetMethod("ToString", new Type[] { typeof(string) }); 

var x = typeof(DateTime).GetMethod("ToString", new Type[] { }); 

或 ...

1

這取決於ToString()方法的重載哪個你想:

var method = typeof(DateTime).GetMethods() 
           .Where (item => item.Name == "ToString" && 
               item.GetParameters().Count() == 0); 

// this is the DateTime.Now.ToString() method without any parameter