小编jam*_*eff的帖子

是否有一种解决方法使C#无法使用类型约束推断泛型类型参数?

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>
{
}
Run Code Online (Sandbox Code Playgroud)

和工厂:

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());
    }
}
Run Code Online (Sandbox Code Playgroud)

以下所需的代码将无法编译:

    public void WontCompile()
    {
        C c = new C();
        var v = Factory1.Create(c); // won't compile
    }
Run Code Online (Sandbox Code Playgroud)

错误消息是"错误CS0411:方法'yo.Factory1.Create(T)'的类型参数无法从用法中推断出来.请尝试明确指定类型参数.",这与Eric在他的博客中所说的一致帖子.

因此,我们可以简单地明确指定泛型类型参数,因为错误消息表明:

    public void SpecifyAllTypes() …
Run Code Online (Sandbox Code Playgroud)

c# generics type-inference

10
推荐指数
1
解决办法
599
查看次数

标签 统计

c# ×1

generics ×1

type-inference ×1