Question

I can understand the Type.GetType() 's Scenario which the Object's type will be got, but what is Type.GetElementType() and what does it do?

Can anyone explain it in a clear way?

Était-ce utile?

La solution

Type.GetElementType is used for arrays, pointers, and by-ref parameter types. For example:

object value = new int[100];
Console.WriteLine(value.GetType()); // System.Int32[]
Console.WriteLine(value.GetType().GetElementType()); // System.Int32

Or:

public void Foo(ref int x) {}
...
var method = typeof(Test).GetMethod("Foo");
var parameter = method.GetParameters()[0];
Console.WriteLine(parameter.ParameterType); // System.Int32&
Console.WriteLine(parameter.ParameterType.GetElementType()); // System.Int32

As for when you'd use them - well, it depends what you're using reflection for to start with.

Autres conseils

GetElementType is for use with arrays, not other generic classes

For more detail Refer This link

Type.GetElementType gets the Type of the object encompassed or referred to by the current array, pointer or reference type. For example:

using System;
class TestGetElementType 
{
    public static void Main() 
    {
        int[] array = {1,2,3};
        Type t = array.GetType();
        Type t2 = t.GetElementType();
        Console.WriteLine("The element type of {0} is {1}.",array, t2.ToString());
        TestGetElementType newMe = new TestGetElementType();
        t = newMe.GetType();
        t2 = t.GetElementType();
        Console.WriteLine("The element type of {0} is {1}.", newMe, t2==null? "null" : t2.ToString());
    }
}

Outputs:

The element type of System.Int32[] is System.Int32.
The element type of TestGetElementType is null.
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top