How to get .NET array type from the string “string

2019-08-09 23:05发布

问题:

Given the string "string[]" and asked to get the underlying Type for this class, one might start with:

private Type getTypeByName(string typeName)
{
    if (typeName.EndsWith("[]"))
    {
           return something; // But what? 
    }

    return Type.GetType(typeName);
}

What type is "string[]" and how does one reflect the type out of it?

Obviously there's a System.String type and a System.Array type, but I can't see how they can be reflected "together" as you would normally do for Nullable<T> and its T with the MakeGenericType method.

Any help to break the mind-loop I've gotten myself into will be greatly appreciated!

回答1:

What exactly is your problem? Type.GetType works fine:

Console.WriteLine(typeof(string[]));
var type = Type.GetType("System.String[]");
Console.WriteLine(type);

Prints:

System.String[]
System.String[]

so clearly this works as expected.



回答2:

Use GetElementType() on the type:

string[] eee = new string[1];
Type ttt = eee.GetType().GetElementType();

ttt is of type String.



回答3:

Type.GetType("System.String[]") will returns the string array type. No need to check for [] in your input string.

You can verity this by checking the Type.IsArray prop.



回答4:

The type is System.String[]