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

2019-08-09 23:18发布

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!

4条回答
甜甜的少女心
2楼-- · 2019-08-09 23:41

Use GetElementType() on the type:

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

ttt is of type String.

查看更多
Juvenile、少年°
3楼-- · 2019-08-09 23:51

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.

查看更多
ら.Afraid
4楼-- · 2019-08-09 23:51

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.

查看更多
手持菜刀,她持情操
5楼-- · 2019-08-09 23:52

The type is System.String[]

查看更多
登录 后发表回答