Create an instance of a class from a string

2018-12-31 07:27发布

Is there a way to create an instance of a class based on the fact I know the name of the class at runtime. Basically I would have the name of the class in a string.

9条回答
皆成旧梦
2楼-- · 2018-12-31 08:17

Probably my question should have been more specific. I actually know a base class for the string so solved it by:

ReportClass report = (ReportClass)Activator.CreateInstance(Type.GetType(reportClass));

The Activator.CreateInstance class has various methods to achieve the same thing in different ways. I could have cast it to an object but the above is of the most use to my situation.

查看更多
何处买醉
3楼-- · 2018-12-31 08:20

Take a look at the Activator.CreateInstance method.

查看更多
时光乱了年华
4楼-- · 2018-12-31 08:20

I know I'm late to the game... but the solution you're looking for might be the combination of the above, and using an interface to define your objects publicly accessible aspects.

Then, if all of your classes that would be generated this way implement that interface, you can just cast as the interface type and work with the resulting object.

查看更多
登录 后发表回答