我想以一种高效的方式实现我的通用IQueue<T>
接口,如果T是struct,则执行一个实现;如果T是类,则执行另一个实现。
interface IQueue<T> { ... }
class StructQueue<T> : IQueue<T> where T : struct { ... }
class RefQueue<T> : IQueue<T> where T : class { ... }
我希望有一个基于T类的工厂方法返回一个或另一个实例:
static IQueue<T> CreateQueue<T>() {
if (typeof(T).IsValueType) {
return new StructQueue<T>();
}
return new RefQueue<T>();
}
当然,编译器指示T应该分别是非空/空类型参数。
是否有方法将T转换为struct类(并将其转换为类类型)以使方法编译?这种运行时调度甚至可以在C#中实现吗?
发布于 2015-12-21 14:54:14
您可以使用反射这样做:
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)));
}
此代码使用方法在运行时创建队列。此方法接受要创建的对象的类型。
若要创建表示泛型类的Type
,此代码使用方法从开放泛型类型(如StructQueue<>
)创建封闭的泛型Type
对象。
发布于 2015-12-21 18:35:37
Yacoub的答案是正确的,但是只要稍加修改,您就不需要对每个对CreateQueue的调用运行CreateQueue。
下面的代码每种类型运行一次MakeGenericType,因为每种类型的QueueFactory<T>
都存在一个单独的静态变量,即QueueFactory<int>.queueType
将获得StructQueue<int>
,而QueueFactory<string>.queueType
将获得RefQueue<int>
public class QueueFactory<T>
{
static Type queueType = typeof(T).IsValueType ?
typeof(StructQueue<>).MakeGenericType(typeof(T)) : typeof(RefQueue<>).MakeGenericType(typeof(T));
public static IQueue<T> CreateQueue()
{
return (IQueue<T>)Activator.CreateInstance(queueType);
}
}
在我的半科学测试中,它在大约十分之一的时间里创造了100万个实例。
https://stackoverflow.com/questions/34405663
复制