【问题标题】:Cannot get selected type from GetTypes无法从 GetTypes 获取所选类型
【发布时间】:2011-09-27 00:16:10
【问题描述】:

我想初始化以下程序集中的类,这些类使用反射继承自 EntityBase 类。

我猜 lambda 表达式是正确的,但我不知道如何从 types2 获取这 2 个类(程序集中有 2 个类继承 EntityBase)。

Assembly a = Assembly.LoadFrom("X:\\Workspace\\Operations\\ItemSupplierSetupRequest\\Main\\Source\\ItemSupplierSetupRequest.Entity\\bin\\Debug\\xxxx.ItemSupplierSetupRequest.Entity.dll");
IEnumerable<Type> types2 =
    a.GetTypes().Where(x => x.BaseType.ToString().Equals("xxxx.ItemSupplierSetupRequest.Entity.EntityBase"));

我也试过了

var result =
    a.GetTypes().Where(x => x.BaseType.FullName.Equals("xxxx.ItemSupplierSetupRequest.Entity.EntityBase"));

但不知道如何使用或检查这是否返回这 2 个类?

【问题讨论】:

    标签: c# reflection lambda expression


    【解决方案1】:

    您的查询应该可以工作。但是没有必要使用Equals() 或使用字符串比较类型。您可以使用(假设EntityBase 在引用的程序集中,并且其命名空间在using 中):

    a.GetTypes().Where(x => x.BaseType == typeof(EntityBase))
    

    请记住,这不会返回从EntityBase 继承的所有类型,只会返回那些直接继承自它的类型。

    【讨论】:

    • 感谢您的回答 - 但我不知道如何使用 Activator.CreateInstance 实例化来自 IEnumerable types2 的对象或我尝试过的 var 结果?有什么线索吗?另外我不知道如何检查我的查询是否返回正确的结果——当然我无法调试 lambda 表达式。谢谢!
    • 如果你还有问题,那就再问一个问题,这样以后有同样问题的人也能找到。您可以调试 lambda 的结果。在 VS 调试器中,您可以点击“结果视图”。
    猜你喜欢
    • 2017-09-18
    • 1970-01-01
    • 2021-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-04
    • 1970-01-01
    相关资源
    最近更新 更多