如何从 Type.GUID 创建对象
我有一组继承自同一基类的类,我需要创建一个工厂方法,用于基于附加到实现类的 GuidAttribute 来实例化不同的基类实现。所以基本上情况是这样的:
abstract class Foo
{
/* ... */
public static Foo Create(Guid guid) {
Type type;
// Resolve the type ?
return Activator.CreateInstance(type) as Foo;
}
}
[Guid("<guid1>")]
class Bar : Foo { ... }
[Guid("<guid2>")]
class Baz : Foo { ... }
除了迭代加载的程序集中的所有类型并缓存结果之外,还有其他方法吗?
I have a set of classes that inherit from the same base class and I need to create a factory method for instantiation of the different base class implementations based on the GuidAttribute attached to the implementing class. So basically the scenario is like this:
abstract class Foo
{
/* ... */
public static Foo Create(Guid guid) {
Type type;
// Resolve the type ?
return Activator.CreateInstance(type) as Foo;
}
}
[Guid("<guid1>")]
class Bar : Foo { ... }
[Guid("<guid2>")]
class Baz : Foo { ... }
Is there any other way than iterating all the types in the loaded assemblies and caching the results?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它不会是自动的,但您可以简单地构建一个
Dictionary
或者如果每个程序集(ala 插件架构)中有一个公共接口/类,则请求它相应地注册类型。没有必要对所有事情都使用反射:)我发现它在很多情况下不太优雅。
It wouldn't be automatic but you could simply build a
Dictionary<Guid,Type>
or if there's a common interface/class in each assembly (ala plugin architecture) request it register the types accordingly.There's no need to use reflection for everything :) I find it less elegant in many cases.
我不认为还有其他方法。当然,我就是这么做的。
I don't think there is another way. Certainly, that is how I would do it.