確定這一個我百思不得其解。我有一個名爲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()
順便說一句,'反對t'應該是'型t';這將避免內部演員。 – SLaks
更改謝謝:-) – MajinFro