简体   繁体   中英

Confused in Type.GetType

I was reading C# in depth and I couldn't understand the para of the chapter

Another method—this time one that already existed in .NET 1.1—that's worth exploring is Type.GetType(string) , and its related Assembly.GetType(string) method, both of which provide a dynamic equivalent to typeof . You might expect to be able to feed each line of the output of listing 3.11 to the GetType method called on an appropriate assembly, but unfortunately life isn't quite that straightforward. It's fine for closed constructed types—the type arguments just go in square brackets. For generic type definitions, though, you need to remove the square brackets entirely— otherwise GetType thinks you mean an array type. Listing 3.12 shows all of these methods in action.

and in the example code author did what he asked not to do I believe :

string listTypeName = "System.Collections.Generic.List`1";
Type defByName = Type.GetType(listTypeName);

Type closedByName = Type.GetType(listTypeName + "[System.String]"); // did here ? , since he passed the listTypeName + [Type args] , so compiler should think it's array?
Type closedByMethod = defByName.MakeGenericType(typeof(string));

or might I got the things wrong , can anyone please elaborate with examples what he meant by line "For generic type definitions, though, you need to remove the square brackets entirely— otherwise GetType thinks you mean an array type"

System.Collections.Generic.List`1[System.String] is the name of the closed generic type.

And the name of the open generic type is not System.Collections.Generic.List`1[] but System.Collections.Generic.List`1 .

That's basically all that this paragraph says.

.Net type names passed by string use [<type1>(,<typeN>)] to indicate a generic type/function parameter list. [] on it's own indicates an array type.

Also, any generic type name will have the construct:

`n

After its string name to indicate the number of generic parameters that the type has. So:

MyNamespace.MyType`1

References the open generic type MyNamespace.MyType<> (ie with no generic arguments supplied).

Whereas

MyNamespace.MyType`1[System.String]

References the closed generic type MyNamespace.MyType<string> .

Note that there are further rules to do with Type.GetType - that being that you can only omit the assembly name (including public key token if applicable) when either:

  1. The type requested can be found in the calling assembly
  2. The type request is in mscorlib .

So, many core types can be specified by string with just their namespace-qualified name, including the generics - and the same goes for when a type name is specified as a type argument (as with System.String above).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM