通用约束和接口实现/继承 [英] Generic constraints and interface implementation/inheritance

查看:108
本文介绍了通用约束和接口实现/继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不完全确定如何解释这个问题,因为它是为什么这不起作用?类型的查询。

Not entirely sure how to phrase the question, because it's a "why doesn't this work?" type of query.

我将特定问题简化为此代码:

I've reduced my particular issue down to this code:

public interface IFoo
{
}

public class Foo : IFoo
{
}

public class Bar<T> where T : IFoo
{
    public Bar(T t)
    {
    }

    public Bar()
        : this(new Foo()) // cannot convert from 'Foo' to 'T'
    {
    }
}

现在,在 Bar< T> T >必须实现IFoo。那为什么编译器会给我评论中的错误?当然,Foo的一个实例是IFoo,因此可以作为泛型类型的代表 T

这是一个编译器限制还是缺少一些东西?

Is this a compiler limitation or am I missing something?

推荐答案

你也可以有一个实现IFoo的Fiz以任何其他方式与Foo相关:

You could also have a Fiz that implements IFoo that is not related to Foo in any other way:

public interface IFoo
{
}

public class Foo : IFoo
{
}

public class Fiz : IFoo
{
}

Foo foo = new Foo();
Fiz fiz = foo; // Not gonna compile.

你想要的可能更像是:

What you want is probably more like:

public class Bar<T> where T : IFoo, new()
{
    public Bar(T t)
    {
    }

    public Bar()
        : this(new T()) 
    {
    }
}

所以你可以有

So you can have

Bar<Foo> barFoo = new Bar<Foo>();
Bar<Fiz> barFiz = new Bar<Fiz>();

这篇关于通用约束和接口实现/继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆