我正在寻找一种方法将对象转换为几种不同类型的结构之一。我需要结构,因为我需要它不可为空。我不确定该怎么做,但这是我迄今为止尝试过的方法,但它不起作用,因为: “对象必须实现 IConvertible。” <- 尝试 Convert.ChangeType
public class Something
{
private object[] things;
public Something()
{
//I don't know at compile time if this will
//be an array of ThingA's or ThingB's
things = new object[1];
things[0] = new ThingA();
ThingA[] thingsArrayA = GetArrayofThings<ThingA>();
things[0] = new ThingB();
ThingB[] thingsArrayB = GetArrayofThings<ThingB>();
}
public TData[] GetArrayofThings<TData>() where TData : struct
{
return (TData[])Convert.ChangeType(things, typeof(TData[]));
}
}
[Serializable]
public struct ThingA
{
//...
}
[Serializable]
public struct ThingB
{
//...
}
感谢 Serg 的回答,这是有效的实现:
public TData[] GetArrayofThings<TData>() where TData: struct
{
return things.OfType<TData>().ToArray<TData>();
}
我仍然对 .ToArray() 的任何惩罚感到好奇,因为这是将被发送到流对象的数据,并且可能有很多。
最佳答案
在我看来,一些 LINQ 查询就足够了。
//getting only ThingA from mixed array
IEnumerable<ThingA> thingsA = things.OfType<ThingsA>()
//we know type of thins inside array, so we just need type conversion
IEnumerable<ThingB> thingsB = things.Cast<ThingB>()
不要使用Convert
,它用于真正的转换(例如,string
到int
),并且你所拥有的是类型转换。
关于c# - 使用泛型将对象转换为结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11693330/