简体   繁体   English

从数组获取实际类型

[英]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) ? 如何使用反射来查看项目,并获得typeof(SomeColour)而不是typeof(IColour) Using what i'm familiar with, typeof(items).GetElementType() gives me IColour , not the actual type. 使用我熟悉的类型, typeof(items).GetElementType()给我IColour ,而不是实际类型。

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 . 数组的类型为IColor The type of the item stored at index 0, is SomeColour . 存储在索引0处的项目的类型为SomeColour What if you added a second item to the array: AnotherColour . 如果将第二个项目添加到数组AnotherColourAnotherColour What should be the type of items ? 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. 您可以使用items[index].GetType()获得存储在数组中的项目的类型,其中index指向数组中的位置。

Maybe this? 也许这个吗?

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

t should be SomeColur, OtherColur etc. t应该是SomeColur,OtherColur等。

typeof(items).GetElementType IS IColor , because it's a list of IColor. typeof(items).GetElementTypeIColor ,因为它是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 . 如果您具有IColor[] ,那么关于“实际类型”只能说的是: IColor For example, you could have: 例如,您可能有:

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

and have an IColor[] array with 2 Foo and 3 Bar . 并具有一个带有2 Foo和3 BarIColor[]数组。 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 这只是@Wouter de kort所说的一个例子

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
{ }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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