开发者

How to create object from its Type.GUID

I have a set of classes that inherit from the sam开发者_开发百科e 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜