2015-10-31 37 views
1

我想找到Enumerable的類型。我的代碼是這樣的:linq命令有什麼問題?

Type[] intLikeTypes = new[] { typeof(int), typeof(decimal), typeof(long), typeof(float) }; 
List<int> columnValue = new List<int>(); 
columnValue.Add(1); 
columnValue.Add(2); 

var listType = columnValue.GetType().GetGenericArguments()[0]; 
Type listGenericType = columnValue.GetType().GetGenericTypeDefinition(); 
if (listGenericType == typeof(List<>)) 
{ 
    bool isInstanceOfTypeInt = (listType == typeof(int)); 
    if (intLikeTypes.Any(x => x.IsInstanceOfType(listType))) 

     resColumnValue=preProcessValue(columnVal, false, false); 

    else if (listType is string) 

     resColumnValue=preProcessValue(columnVal, true, false); 

} 
當我使用 bool isInstanceOfTypeInt = (listType == typeof(int))

,該isInstanceOfTypeInttrue。但是,if(intLikeTypes.Any(x => x.IsInstanceOfType(listType))的條件是false。爲什麼x.IsInstanceOfType(listType)無法正確找到實例?

順便說一下,linq命令正在爲list<int>類型以外的columnValue工作。例如,它適用於int類型。

+0

如果你想比較類型只是做'intLikeTypes.Any(X => X == listType)'因爲X已經是一個'Type'。 – thepirat000

+0

謝謝@ thepirat000!在建議的答案中看到我的評論! –

+0

'intLikeTypes'的一個更好的名字是'numericTypes';) –

回答

2

更換條件

if (intLikeTypes.Any(x => x.IsInstanceOfType(listType))) 

if (intLikeType.Any(x => x == listType)) 

順便說一句,在條件

if (listGenericType == typeof(List<>)) 

總是被判斷爲真,我認爲沒有理由評估這到假。

UPDATE

方法IsInstanceOfType確定變量的「類型」是一種特定類型的,它並不確定,如果該類型是一樣的另一種類型(的情況下,你的代碼做什麼)

例如,考慮下面的例子

int s = 5; 
bool test = typeof(int).IsInstanceOfType(s); 

「測試」變量的值將是正確的,因爲s變量的類型是int

,但下面的代碼將評估爲假

Type intType = typeof(int); 
bool test = typeof(int).IsInstanceOfType(intType); 

這裏的「測試」變量將具有值「假」,因爲變量「IntType上」,這類型的「類型」是不是int

這裏是這種方法的文檔的一部分

返回值

類型:System.Boolean

如果當前類型是在用○表示的對象的繼承層次結構,或者如果當前類型是一個實現的接口。如果這兩個條件都不是這種情況,則爲false,如果o爲null,或者當前Type爲開放泛型類型(即ContainsGenericParameters返回true)。

看到這種方法的文檔的詳細信息。

https://msdn.microsoft.com/en-us/library/system.type.isinstanceoftype(v=vs.110).aspx

+0

謝謝@Hakam Fostok!但我的問題是爲什麼'IsInstanceOfType'在這種情況下不起作用,因爲它適用於其他類型!我用'if(listGenericType == typeof(List <>))'因爲我有其他類型!這只是一個例子! –

+0

你的意思是這個語句的條件是true bool isInstanceOfTypeInt =(listType == typeof(long));如果你的意思是你說的不對,那麼這根本就不起作用 –

+0

是的!你是對的!它只適用於int類型,但爲什麼它不適用於其他人!? –