我有一个类,它实现这样的接口;
... = new Location<ICafe>();
... = new Location<IBusiness>();
etc如果我想扩大Location类型的数量,我现在需要编辑代码。
有什么方法可以根据接口的字符串名称实例化类吗?
因此,我将从数据库中获取Cafe或Business,我希望使用接口的字符串名称实例化上面的内容。
编辑
我应该注意,我在代码中使用了ICafe、IBusiness等,以确定这是什么类型的项目,以及在屏幕上显示什么。
发布于 2012-02-27 02:20:40
是的,反射将允许您这样做,但是有几个步骤:
ifaceType = Type.GetType(string)
System.Type,例如,与泛型类型模板对应的System.Type,从任何参数集开始,例如genericType = typeof (Location).GetGenericTypeDefinition()
specificType = genericType.MakeGenericType(ifaceType)
Activator.CreateInstance(specificType)发布于 2012-02-27 02:24:19
在我看来,你可能会受益于更抽象。是否有什么原因不能让一个名为“超级接口”的超级接口:
interface IAbstractLocation 然后,使用适当的接口创建具体的类,但是使用这些接口继承AbstractLocation类型:
interface ICafe : IAbstractLocation
interface IBusiness : IAbstractLocation然后,您将有1种类型:
...Location<IAbstractLocation>();它应该处理从IAbstractLocation接口继承的任何可能添加的新类型。
https://stackoverflow.com/questions/9459248
复制相似问题