gpt4 book ai didi

c# - 使用反射创建命名空间中所有类的列表并转换为它们的真实类型

转载 作者:行者123 更新时间:2023-11-30 21:37:44 25 4
gpt4 key购买 nike

我有一个抽象类 Device。许多类派生自它,代表特定的设备。所以我们有,例如class RedDevice : Deviceclass BlueDevice : Device 等。它们都存储在 Foo.Devices 命名空间下。以下是结构的概述:

- Foo
| ↳ Devices (folder)
| | ↳ RedDevice
| | ↳ BlueDevice
| ↳ Device

Device.cs:

internal abstract class Device
{
internal string Path { get; set; }
}

RedDevice.cs:

class RedDevice
{
internal RedDevice()
{
this.Path = "/path";
}
}

我想创建一个列表,其中包含 Foo.Devices 下的所有设备,并将其转换为它们的父类 Device。我可以使用以下代码获取 Type 的列表:

List<System.Type> deviceTypes = 
Assembly.GetExecutingAssembly().GetTypes().Where(t => t.Namespace ==
typeof(RedDevice).Namespace).ToList();

但是我怎样才能将它们转换为 Device?编译器不允许直接强制转换,其他一切都会抛出错误的类型异常。谢谢!

最佳答案

您的deviceTypes 列表包含类型(类定义),而不是类实例。因此,在将它们转换到 Device 之前,您需要创建它们的实例。

如果他们有无参数的构造函数,你可以使用:

List<Device> devices = new List<Device>();
foreach (Type deviceType in deviceTypes)
{
devices.Add((Device)Activator.CreateInstance(deviceType));
}

如果其中一个类确实需要构造函数参数,可能很难弄清楚如何提供这些参数。

关于c# - 使用反射创建命名空间中所有类的列表并转换为它们的真实类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46957326/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com