2012-05-23 68 views
2

確定這一個我百思不得其解。我有一個名爲Testbase的抽象基類,它有一個名爲RunTest的抽象函數。在一個文件夾中,我有一個繼承這個抽象類的類的集合。在測試控制器中,我調用以下代碼來創建這些測試類的實例列表。使用Lambda表達式原因更改爲類類型

 String ns = "HCTCommon.Tests"; 
     var query = from t in Assembly.GetExecutingAssembly().GetTypes() 
        where t.Namespace == ns 
        select t; 

     foreach (object t in query) 
     { 
      TestBase test = (TestBase)Activator.CreateInstance(t as Type); 
      testList.Add(test); 
     } 

在類的runTest函數的一個我一直在清理代碼,並決定使用lambda表達式和嘗試過各種版本。

pullservice = ServiceController.GetServices().FirstOrDefault(s => s.ServiceName == serviceName); 

pullservice = ServiceController.GetServices().Where(s => s.DisplayName.Equals("Pull Service")).ToList()[0]; 

是我記得的那些,但每當我使用拉姆達的,而不是通過一些令人費解的foreach循環我得到的代碼

TestBase test = (TestBase)Activator.CreateInstance(t as Type); 

行了一個InvalidCastException運行例外:

Unable to cast object of type '<>c__DisplayClass4' to type 'HCTCommon.TestBase'. 

Stack Trace: 

    at HCTCommon.TestController.populateTestList() 
    at HCTCommon.TestController..ctor(RegistryKey Key) 
    at HealthCheck.HealthCheckForm.InitializeTestPanels() in C:\Users\bkoch.ESI911\documents\visual studio 2010\Projects\HCTCommon\HealthCheck\HealthCheckForm.cs:line 55 
    at HealthCheck.HealthCheckForm..ctor() in C:\Users\bkoch.ESI911\documents\visual studio 2010\Projects\HCTCommon\HealthCheck\HealthCheckForm.cs:line 26 
    at HealthCheck.Program.registrycheck() in C:\Users\bkoch.ESI911\documents\visual studio 2010\Projects\HCTCommon\HealthCheck\Program.cs:line 63 
    at HealthCheck.Program.Main() in C:\Users\bkoch.ESI911\documents\visual studio 2010\Projects\HCTCommon\HealthCheck\Program.cs:line 34 
    at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args) 
    at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) 
    at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() 
    at System.Threading.ThreadHelper.ThreadStart_Context(Object state) 
    at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) 
    at System.Threading.ThreadHelper.ThreadStart() 
+1

順便說一句,'反對t'應該是'型t';這將避免內部演員。 – SLaks

+0

更改謝謝:-) – MajinFro

回答

2

lambda表達式生成一個匿名閉包類來存放局部變量。
您的代碼錯誤地選取了此課程。

您應該添加

where typeof(TestBase).IsAssignableFrom(t) 
+0

謝謝,工作很好。 – MajinFro

1

您需要檢查類型實際上是擴展了Testbase

var testList = (from t in Assembly.GetExecutingAssembly().GetTypes() 
       where t.Namespace == ns && typeof(TestBase).IsAssignableFrom(t) 
       select (TestBase)Activator.CreateInstance(t) 
       ).ToList(); 
+0

由於某種原因,當試用這個它不會找到任何類,但只是添加&& typeof原始查詢似乎解決了問題 – MajinFro

相關問題