如何使用Type.GetType()获取类型并实例化对象?附实例场景问询
Hey there! Let's walk through your two questions about working with Type objects and instantiation in C#—I'll keep it practical with code examples so you can follow along easily.
First, Type.GetType() requires you to pass the fully qualified type name (that's the namespace plus the class name) to retrieve the Type object. A quick note: if the type is in the current assembly or mscorlib, you can just use the fully qualified name. If it's in another assembly, you'll need to include the assembly name too.
Step 1: Get the Type object
Here's a basic example with a custom class:
// Assume we have this class in the MyApp namespace namespace MyApp { public class MySampleClass { public MySampleClass() { } public MySampleClass(string message) { Console.WriteLine(message); } } } // Get the Type object Type myType = Type.GetType("MyApp.MySampleClass"); // If the class is in a different assembly, use: // Type myType = Type.GetType("MyApp.MySampleClass, MyOtherAssembly");
Step 2: Instantiate the object
Once you have the Type, use Activator.CreateInstance() to create an instance. There are overloads for both parameterless and parameterized constructors:
- Parameterless constructor:
if (myType != null) { object instance = Activator.CreateInstance(myType); // Cast to your class type if needed MySampleClass typedInstance = instance as MySampleClass; }
- Parameterized constructor:
Pass the constructor arguments as an object array:
if (myType != null) { object[] constructorArgs = new object[] { "Hello from the constructor!" }; object instance = Activator.CreateInstance(myType, constructorArgs); MySampleClass typedInstance = instance as MySampleClass; }
Great, you already have the Type object from an existing instance (packet.GetType()). Now instantiating it works similarly, but you have a few options depending on your needs:
Option 1: Use a parameterless constructor
If the type has a public parameterless constructor, this is the simplest way:
Type typesample = packet.GetType(); object newInstance = Activator.CreateInstance(typesample); // If you know the base type or interface, cast it to that // e.g., if packet is of type BasePacket, you can do: // BasePacket newPacket = newInstance as BasePacket;
Option 2: Use a parameterized constructor
If you need to pass arguments to the constructor, you can either:
- Use the overload of
Activator.CreateInstance()that takes arguments:
// Assume the constructor takes an int and a string object[] args = new object[] { 123, "Test data" }; object newInstance = Activator.CreateInstance(typesample, args);
- Or explicitly get the ConstructorInfo and invoke it (useful if you need more control, like handling non-public constructors):
// Get the constructor that takes an int and string ConstructorInfo ctor = typesample.GetConstructor(new Type[] { typeof(int), typeof(string) }); if (ctor != null) { object newInstance = ctor.Invoke(new object[] { 123, "Test data" }); }
Option 3: Handle value types or non-public types
If typesample is a value type (like int, DateTime), Activator.CreateInstance() will still work—it'll return a default instance. For non-public constructors, you can use overloads of GetConstructor() or Activator.CreateInstance() that specify BindingFlags to access them.
Just remember to add null checks (like checking if typesample is valid, or if the constructor exists) to avoid runtime exceptions!
内容的提问来源于stack exchange,提问作者jack Chen

