c# - 使用泛型将对象转换为结构

标签 c# generics struct

我正在寻找一种方法将对象转换为几种不同类型的结构之一。我需要结构,因为我需要它不可为空。我不确定该怎么做,但这是我迄今为止尝试过的方法,但它不起作用,因为: “对象必须实现 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,它用于真正的转换(例如,stringint),并且你所拥有的是类型转换

关于c# - 使用泛型将对象转换为结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11693330/

相关文章:

c++ - 相同类型的类成员之间的填充总是相同的吗?

c++ - 从具有多种类型的 C++ 文件中读取结构

c++ - 简单的 "identifier ' xxx' 未定义"使用结构

c# - 从一种 PixelFormat 转换为另一种 WPF

c# - 如何通过用户凭据访问 AD FS 声明?

c# - ConcurrentBag 与自定义线程安全列表

c# - 确定类是否是具有多个泛型参数的类型的子类

Python 实例方法与静态方法

c# - 为什么 Int32 类型的最大值为 2³¹ − 1?

generics - 从具有 null 的静态函数返回 Template<T?> 时如何获取正确的类型