给定泛型类的当前结构。
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>中派生出来。
改到
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>类型的对象是固定的(因为它的减号)。
发布于 2016-06-20 17:09:49
我想您必须结束泛型递归循环:
一般接口:
public interface IFoo
{
}
public interface IBar
{
}取决于您想要的继承类型:
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
{
}或者:
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
{
}摘要类:
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
{
}实施课程:
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>
{
}用法:
var test = new Foo<IFoo<IFoo<IFoo, IBar<IFoo, IBar>>, IBar>, IBar>();我仍然不明白你想在这里完成什么,用一个更好的解释,应该有一个更好的解决方案。
https://stackoverflow.com/questions/37926318
复制相似问题