The most efficient method of obtaining a Type object for a specific type is to use the typeof operator shown here.
System.Type t1 = typeof(System.Text.StringBuilder);
The type name isn't enclosed in quotes and must be resolvable by the compiler. Because the reference is resolved at compile time, the assembly containing the type becomes a static dependency of your assembly and will be listed as such in your assembly's manifest.
An alternative to the typeof operator is the static method Type.GetType, which takes a string containing the type name. Because you use a string to specify the type, you can vary it at run time, which opens the door to a world of dynamic programming opportunities using reflection. If you specify just the type name, the runtime must be able to locate the type in an already loaded assembly. Alternatively, you can specify an assembly-qualified type name. Refer to the .NET Framework SDK documentation for the Type.GetType method for a complete description of how to structure assembly-qualified type names.
The following statements demonstrate the use of the GetType method:
// Case sensitive, return null if not found Type t2 = Type.GetType("System.String"); // Case sensitive, throw TypeLoadException if not found Type t3 = Type.GetType("System.String", true); // Case insensitive, throw TypeLoadException if not found Type t4 = Type.GetType("system.string", true, true); // Assembly qualifed type name Type t5 = Type.GetType("System.Data.DataSet,System.Data," + "Version=1.0.5000.0,Culture=neutral,PublicKeyToken=b77a5c561934e089");
To obtain a Type object representing the type of an existing object, use the GetType method, implemented by Object and inherited by all types.
Here's an example:
System.Text.StringBuilder sb = new System.Text.StringBuilder(); Type t6 = sb.GetType();
Method | Description |
---|---|
Type.GetNestedType | Gets a specified type declared as a nested type within the existing Type object |
Type.GetNestedTypes | Gets an array of Type objects representing the nested types declared within the existing Type object |
Assembly.GetType | Gets a Type object for the specified type declared within the assembly |
Assembly.GetTypes | Gets an array of Type objects representing the types declared within the assembly |
Module.GetType | Gets a Type object for the specified type declared within the module |
Module.GetTypes | Gets an array of Type objects representing the types declared within the module |
Module.FindTypes | Gets a filtered array of Type objects representing the types declared within the module—the types are filtered using a delegate that determines if each Type should appear in the final array |
No comments:
Post a Comment