Eric Lippert在http://blogs.msdn.com/b/ericlippert/archive/2009/12/10/constraints-are-not-part-of-the-signature.aspx的博客文章中解释了为什么类型推断不考虑约束,这是有道理的,因为方法不能通过简单地改变类型约束来重载。然而,我想找到一种方法来实例化一个对象,使用两个泛型类型,一个可以推断,另一个可以推断,如果考虑到约束,而不必指定任何类型。
给定类型:
public interface I<T>
{
Other<T> CreateOther();
}
public class C : I<string>
{
public Other<string> CreateOther()
{
return new Other<string>();
}
}
public class Other<T>
{
}
和工厂:
public static class Factory1
{
public static Tuple<T, Other<T1>> Create<T, T1>(T o) where T : I<T1>
{
return new Tuple<T, Other<T1>>(o, o.CreateOther());
}
}
下面的代码将无法编译:
public void WontCompile()
{
C c = new C();
var v = Factory1.Create(c); // won't compile
}
错误消息是"错误CS0411:不能从用法中推断出方法'yo.Factory1.Create(T)'的类型参数。尝试显式指定类型参数。",这与Eric在他的博客文章中所说的一致。
因此,我们可以简单地显式指定泛型类型参数,如错误消息所示: public void SpecifyAllTypes()
{
C c = new C();
var v = Factory1.Create<C, string>(c); // type is Tuple<C, Other<string>>
}
如果不希望指定类型参数,也不需要保留C类型,可以使用以下工厂:
public static class Factory2
{
public static Tuple<I<T1>, Other<T1>> CreateUntyped<T1>(I<T1> o)
{
return new Tuple<I<T1>, Other<T1>>(o, o.CreateOther());
}
}
,现在指定:
public void Untyped()
{
C c = new C();
var v = Factory2.CreateUntyped(c); // type is Tuple<I<string>, Other<string>>
}
但是,我希望在返回的对象中保留C类型,而不指定类型。
我想出了一个解决这个问题的方法,但它似乎是一个拼凑的解决方案,其中C类型的对象在两步工厂调用中使用了两次。
要做到这一点,使用以下工厂:public static class Factory3
{
public static Factory<T1> CreateFactory<T1>(I<T1> o)
{
return new Factory<T1>();
}
}
public class Factory<T1>
{
public Tuple<T, Other<T1>> Create<T>(T o) where T : I<T1>
{
return new Tuple<T, Other<T1>>(o, o.CreateOther());
}
}
可以这样使用:
public void Inferred()
{
C c = new C();
var v = Factory3.CreateFactory(c).Create(c); // type is Tuple<C, Other<string>>
}
这感觉很奇怪,因为c被使用了两次。第一次使用时,它实际上被丢弃,因为它只是用来推断基类型参数。
是否有更好的解决方案来解决这个问题,使对象不需要使用两次,也不需要指定类型?
edit:我刚刚意识到,虽然对象必须使用两次,但不需要第二个工厂类。相反,这两个参数可以在同一个工厂方法中使用,如下所示:
public class Factory
{
public Tuple<T, Other<T1>> Create<T, T1>(T o, I<T1> o2) where T : I<T1>
{
return new Tuple<T, Other<T1>>(o, o.CreateOther());
}
}
可以这样使用:
public void Inferred()
{
C c = new C();
var v = Factory.Create(c, c); // type is Tuple<C, Other<string>>
}
这仍然不理想,但比必须创建第二个工厂类要好,并且至少可以使用XMLDoc注释来指示两个参数应该是相同的对象。同样,一个参数(本例中为o2
)仅用于推断T
的约束类型。