简体   繁体   中英

Get actual type from array

Given this example:

IColor[] items;
items = new IColour[]{ new SomeColour() };

How do I use reflection to look at items, and get typeof(SomeColour) rather than typeof(IColour) ? Using what i'm familiar with, typeof(items).GetElementType() gives me IColour , not the actual type.

What you are asking for is not possible. Your array can store multiple items, each having a different concrete type.

The type of your array is IColor . The type of the item stored at index 0, is SomeColour . What if you added a second item to the array: AnotherColour . What should be the type of items ?

You can get the type of the items stored in your array by using items[index].GetType() where index points to the location in your array.

Maybe this?

foreach (var item in items)
{
    var t = item.GetType();
}

t should be SomeColur, OtherColur etc.

typeof(items).GetElementType IS IColor , because it's a list of IColor.

To get a specific elements underlying type:

IColor item = items[<someIdx>];
item.GetType();

If you have an IColor[] , then the only thing you can say about the "actual type" is: IColor . For example, you could have:

class Foo : IColor {...}
class Bar : IColor {...}

and have an IColor[] array with 2 Foo and 3 Bar . Now: what is the "type" ?

If the array is non-empty, you could look at, say, the first item:

var type = items[0].GetType();

But that won't help if the data is heterogeneous. You could check for the distinct types and hope it turns out to be homogeneous:

var type = items.Select(x => x.GetType()).Single();

This is just an example of what @Wouter de kort is saying

internal class Program
{
    private static void Main(string[] args)
    {
        IColour[] items;
        items = new IColour[] { new SomeColour(), new SomeOtherColour() };

        Console.WriteLine(items.GetType().GetElementType().Name);  // Will always return IColour

        foreach (var item in items)
        {
            Console.WriteLine(item.GetType().Name); // Will return the name of type added with the IColour interface
        }

        Console.ReadLine();
    }
}

internal interface IColour
{ }

internal class SomeColour : IColour
{ }

internal class SomeOtherColour : IColour
{ }

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