如果type参数是struct或class,则选择泛型实现

aka*_*okd 5 c# generics

IQueue<T>如果T是struct而另一个是T是一个类,我想通过一个实现以有效的方式实现我的泛型接口.

interface IQueue<T> { ... }

class StructQueue<T> : IQueue<T> where T : struct { ... }

class RefQueue<T> : IQueue<T> where T : class { ... }
Run Code Online (Sandbox Code Playgroud)

我希望有一个基于T类的工厂方法返回一个或另一个的实例:

static IQueue<T> CreateQueue<T>() {
    if (typeof(T).IsValueType) {
        return new StructQueue<T>();
    }
    return new RefQueue<T>();
}
Run Code Online (Sandbox Code Playgroud)

当然,编译器指示T应该分别是非可空/可空类型参数.

有没有办法将T转换为struct类(并进入类类)以使该方法编译?是否可以使用C#进行这种运行时调度?

Yac*_*sad 5

您可以使用Reflection来执行此操作:

static IQueue<T> CreateQueue<T>()
{
    if (typeof(T).IsValueType)
    {
        return (IQueue<T>)Activator
            .CreateInstance(typeof(StructQueue<>).MakeGenericType(typeof(T)));
    }

    return (IQueue<T>)Activator
        .CreateInstance(typeof(RefQueue<>).MakeGenericType(typeof(T)));
}
Run Code Online (Sandbox Code Playgroud)

此代码使用该Activator.CreateInstance方法在运行时创建队列.此方法接受您要创建的对象的类型.

要创建Type表示泛型类的代码,此代码使用该MakeGenericType方法Type从打开的泛型类型创建封闭的通用对象StructQueue<>.