限制C#中泛型的类型参数

时间:2010-07-28 17:23:36

标签: c# java generics

我可能会想象事物,但我似乎在Java中回忆起我可以声明一个字段或参数:

public class BarHandler{

    public Class<? extends Foo> fooType;

    public ProcessedBar Process(string xml){
        Foo foo = fooType.GetInstance();
        return foo.process(xml)
    }
}

这对于工厂样式系统非常有用,例如,您必须能够生成相关类型的新实例。

我试图弄清楚C#中是否存在这种模拟,或者这可能只是Java中可用的东西。

4 个答案:

答案 0 :(得分:5)

是的,请参阅generic constraints。与您的示例相同的是:

public class SomeClass<T>
    where T : Foo
{
    private T fooType;
}

编辑后编辑:我相信你指的是wildcards,在这种情况下,你应该阅读有关仿制药的covariance and contravariance

答案 1 :(得分:1)

public class GenericClass<T> where T : Foo

答案 2 :(得分:1)

您可以使用非常简单的包装来进行此注释和便宜的运行时检查:

public sealed class Type<T>
{
    public Type(Type type)
    {
        if (type == null)
            throw new ArgumentNullException("type");
        if (!typeof(T).IsAssignableFrom(type))
            throw new ArgumentException(string.Format("The specified type must be assignable to '{0}'.", typeof(T).FullName));

        this.Value = type;
    }

    public Type Value
    {
        get;
        private set;
    }
}

使用Activator.CreateInstance实际创建该类型的实例。假设FooDerived来自Foo

Type<Foo> fooType = new Type<Foo>(typeof(FooDerived));
Activator.CreateInstance(fooType.Value);

答案 3 :(得分:1)

这是280Z28答案的变体。我已将“Type”类重命名为“Factory”,因为在我的版本中,它公开了GetInstance方法而不是类型为Value的{​​{1}}属性。这使用2个通用参数和通用约束来强制执行Type类的原始答案构造函数中的规则。

Type
相关问题