gpt4 book ai didi

c# - 在c#中将动态对象转换为动态类型的数组

转载 作者:太空宇宙 更新时间:2023-11-03 12:52:55 24 4
gpt4 key购买 nike

我有两种类型:

    public class Type1
{
public string Name { get; set; }
}

public class Type2
{
public string Name { get; set; }
}

我有一个元素列表(每个元素都是一个对象类型)。一些元素可以是一个数组。 (数组可以是 type1[] 或 type2[])

我的目标是:
1-迭代我的元素列表
2-确定哪些是 type1[]array pr type2[] array
3-获取先前数组元素的名称值属性

这就是我所做的:

    foreach (var Myobject in MyList)
{
if (myObject.GetType().IsArray)
{
var elementType = myObject.GetType().GetElementType()// should me return the element type, ie Type1 or Type2

//This is where I am stuck, I know that my object is an array but I cannot cast if in type1[] or type2[] array by using elementType
//The following is not working
elementType[] myArrat = (elementType[])myObject;

// And I don't want to hardwrite each case for each possible type like this :
Type1[] myArrat = (Type1[])myObject;
Type2[] myArrat = (Type2[])myObject;
// I want to use the elementType that I got previously

}
}

预先感谢您的帮助。

最佳答案

你不能做你想做的事。坦率地说,您可能也不需要这样做。如果您期望不同的类型,则意味着您将对每种类型执行不同的操作。您可以做的是更改 Type1 和 Type2 以扩展相同的基类并改用基类:

public class TypeBase 
{
public virtual string Name { get; set; }
}

public class Type1 : TypeBase
{
}

public class Type2 : TypeBase
{
}


foreach (var myobject in MyList)
{
if (myObject.GetType().IsArray)
{
object[] array = (object[]) myObject;
TypeBase[] yourArray = array.Cast<TypeBase>();
//use the properties and methods of TypeBase instead of Type1 and Type2
//mark the methods and properties in TypeBase as virtual and
//override them on Type1 and Type2 if needed
}
}

关于c# - 在c#中将动态对象转换为动态类型的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34920363/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com