【发布时间】:2020-11-23 05:24:19
【问题描述】:
我有以下代码,我在数组中添加一些类对象。
Object[] ArrayOfObjects = new Object[] {typeof(Person), typeof(Company)};
现在,如果我想遍历我的类项目,如何将每个项目转换回其原始类型(例如 Person 和 Company)?使用反射也许可以做到这一点,但我想知道 C# 是否有一些内置功能来实现这一点。
foreach (var item in ArrayOfObjects)
{
// TODO Convert item back to Original Type (Person or Company)
// I am doing something like this but not working
var person = Convert.ChangeType(item, typeof(Person));
//I can not do this too as hardcoding the type inside the loop makes no sense
var person = item as Person; //I need to convert item as Person or Company so that i can automate the tasks here.
}
非常感谢。
【问题讨论】:
-
您不必将它转换回它的类型 - 它已经是那种类型。对象的运行时类型(例如
Person)和变量的类型(例如System.Object)不是一回事。 -
请告诉我们你想做什么 - 因为这个问题感觉就像minimal reproducible example。换句话说 - 向我们展示一些示例 TODO 代码,展示您计划如何使用
Person或Company。 -
我怀疑你想要的是
var person = item as Person;然后检查它是否是null。或者foreach (var item in ArrayOfObjects.OfType<Person>()). -
我的意思是如果是一个人你不需要
ChangeType给一个人。它已经是一个(即,如果您调用item.GetType(),它将返回Person)。所以如果item是一个人,那么var person = item as Person;就可以正常工作。 -
但是您的示例
new Object[] {typeof(Person), typeof(Company)};正在做其他事情。这是一个 Type 对象数组,而不是每种类型的实例。
标签: c# arrays .net reflection