使用Lambda表达式会导致更改类类型

时间:2012-05-23 15:35:33

标签: c# .net reflection lambda abstract

好的,这让我感到困惑。我有一个名为Testbase的抽象基类,它有一个名为RunTest的抽象函数。在一个文件夹中,我有一组继承此抽象类的类。在测试控制器中,我调用以下代码来创建这些测试类的实例列表。

        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];

是我记得的那些但是无论何时我使用lambda而不是通过一些复杂的foreach循环我在代码行上得到一个invalidcastexception

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

例外:

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()

2 个答案:

答案 0 :(得分:2)

lambda表达式生成一个匿名闭包类来保存局部变量 您的代码错误地选择了此类。

你应该添加

where typeof(TestBase).IsAssignableFrom(t)

答案 1 :(得分:1)

您需要检查类型是否实际延伸Testbase

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