Create an instance of a class from a string

后端 未结 8 1314
别跟我提以往
别跟我提以往 2020-11-22 02:53

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.

相关标签:
8条回答
  • 2020-11-22 03:32

    Take a look at the Activator.CreateInstance method.

    0 讨论(0)
  • 2020-11-22 03:39

    For instance, if you store values of various types in a database field (stored as string) and have another field with the type name (i.e., String, bool, int, MyClass), then from that field data, you could, conceivably, create a class of any type using the above code, and populate it with the value from the first field. This of course depends on the type you are storing having a method to parse strings into the correct type. I've used this many times to store user preference settings in a database.

    0 讨论(0)
提交回复
热议问题