2014-10-31 56 views
0

我有一个相当简单的方法:提供了类型数组作为方法的参数

public static LinkItemCollection ToList<T>(this LinkItemCollection linkItemCollection) 
{ 
    var liCollection = linkItemCollection.ToList(true); 
    var newCollection = new LinkItemCollection(); 

    foreach (var linkItem in liCollection) 
    { 
     var contentReference = linkItem.ToContentReference(); 
     if (contentReference == null || contentReference == ContentReference.EmptyReference) 
      continue; 

     var contentLoader = ServiceLocator.Current.GetInstance<IContentLoader>(); 
     IContentData content = null; 
     var epiObject = contentLoader.TryGet(contentReference, out content); 
     if (content is T) 
      newCollection.Add(linkItem); 
    } 

    return newCollection; 
} 

这工作得很好 - 我可以调用该方法,并提供一个类型T.不过,我希望能够做到是能够指定多种类型的。因此,我错误地认为我可以重构方法:

public static LinkItemCollection ToList(this LinkItemCollection linkItemCollection, Type[] types) 
{ 
    var liCollection = linkItemCollection.ToList(true); 
    var newCollection = new LinkItemCollection(); 

    foreach (var linkItem in liCollection) 
    { 
     var contentReference = linkItem.ToContentReference(); 
     if (contentReference == null || contentReference == ContentReference.EmptyReference) 
      continue; 

     foreach (var type in types) 
     { 
      var contentLoader = ServiceLocator.Current.GetInstance<IContentLoader>(); 
      IContentData content = null; 
      var epiObject = contentLoader.TryGet(contentReference, out content); 
      if (content is type) 
       newCollection.Add(linkItem); 
     } 
    } 

    return newCollection; 
} 

但是,Visual Studio是显示它无法解决就行if(content is type)类型的符号。

我知道我做错了什么,我猜我需要在这里使用反射。

+0

旁注:你可能希望使用'params'的最后一个参数:',则params类型[]类型)'要能够把它无需手动转换项目阵列。 – 2014-10-31 01:54:12

回答

1

什么你要找的是:

type.IsAssignableFrom(content.GetType()) 

is仅用于对在编译时已知,而不是在运行时类型检查。

+0

好的答案 - 它使我使用IsInstanceOfType。 – dotdev 2014-10-31 10:31:36

相关问题