首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >类型必须是可转换的,才能在泛型类中使用它作为参数。

类型必须是可转换的,才能在泛型类中使用它作为参数。
EN

Stack Overflow用户
提问于 2016-06-20 15:29:02
回答 1查看 2.3K关注 0票数 0

给定泛型类的当前结构。

代码语言:javascript
复制
public abstract class Foo<TFoo, TBar>
    where TFoo : Foo<TFoo, TBar>
    where TBar : Bar<TFoo, TBar>
{
}

public abstract class Foo<TFoo> : Foo<TFoo, BarImpl>
    where TFoo : Foo<TFoo>
{
}

public class FooImpl : Foo<FooImpl>
{
}

public abstract class Bar<TFoo, TBar>
    where TFoo : Foo<TFoo, TBar>
    where TBar : Bar<TFoo, TBar>
{
}

public abstract class Bar<TFoo> : Bar<TFoo, BarImpl>
    where TFoo : Foo<TFoo>
{
}

public class BarImpl : Bar<FooImpl>
{
}

我想要的是在每个Foo<TFoo>实现上设置一个默认的Foo<TFoo>。在代码的其他部分,创建了TBar的一个实例,如果它是Bar<TFoo>,它就会失败,因为这是一个abstract类。

但是,引发了下面的错误,我不知道我能做什么,或者如果可能的话。

类型'BarImpl‘必须转换为'Bar’,以便将其用作泛型类Foo中的参数'TBar‘。

我已经试着让BarImpl从没有效果的Bar<FooImpl, BarImpl>中派生出来。

改到

代码语言:javascript
复制
public abstract class Foo<TFoo> : Foo<TFoo, Bar<TFoo>>
    where TFoo : Foo<TFoo>
{
}

public abstract class Bar<TFoo> : Bar<TFoo, Bar<TFoo>>
    where TFoo : Foo<TFoo>
{
}

将一直工作,直到Bar<TFoo>类型的对象是固定的(因为它的减号)。

EN

回答 1

Stack Overflow用户

发布于 2016-06-20 17:09:49

我想您必须结束泛型递归循环:

一般接口:

代码语言:javascript
复制
public interface IFoo
{
}

public interface IBar
{
}

取决于您想要的继承类型:

代码语言:javascript
复制
public interface IFoo<TFoo> : IFoo
    where TFoo : IFoo
{
}

public interface IBar<TBar> : IBar
    where TBar : IBar
{
}

public interface IFoo<TFoo, TBar> : IFoo<IFoo>
    where TFoo : IFoo
    where TBar : IBar
{
}

public interface IBar<TFoo, TBar> : IBar<IBar>
    where TFoo : IFoo
    where TBar : IBar
{
}

或者:

代码语言:javascript
复制
public interface IFoo<TFoo, TBar> : IFoo
    where TFoo : IFoo
    where TBar : IBar
{
}

public interface IBar<TFoo, TBar> : IBar
    where TFoo : IFoo
    where TBar : IBar
{
}

public interface IFoo<TFoo> : IFoo<TFoo, IBar>
    where TFoo : IFoo
{
}

public interface IBar<TBar> : IBar<IFoo, TBar>
    where TBar : IBar
{
}

摘要类:

代码语言:javascript
复制
public abstract class AFoo<TFoo, TBar> : IFoo<TFoo, TBar>
    where TFoo : IFoo
    where TBar : IBar
{
}

public abstract class ABar<TFoo, TBar> : IBar<TFoo, TBar>
    where TFoo : IFoo
    where TBar : IBar
{
}

实施课程:

代码语言:javascript
复制
public class Foo<TFoo, TBar> : AFoo<TFoo, TBar>
    where TFoo : IFoo
    where TBar : IBar
{
}

public class Bar<TFoo, TBar> : ABar<TFoo, TBar>
    where TFoo : IFoo
    where TBar : IBar
{
}


public class Foo<TFoo> : AFoo<TFoo, IBar>
    where TFoo : IFoo
{
}

public class Bar<TBar> : ABar<IFoo, TBar>
    where TBar : IBar
{
}

public class Foo : AFoo<IFoo, IBar>
{
}

public class Bar : ABar<IFoo, IBar>
{
}

用法:

代码语言:javascript
复制
var test = new Foo<IFoo<IFoo<IFoo, IBar<IFoo, IBar>>, IBar>, IBar>();

我仍然不明白你想在这里完成什么,用一个更好的解释,应该有一个更好的解决方案。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37926318

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档