2016-06-20 29 views
0

給定泛型類的當前結構。該類型必須是可轉換的,才能將其用作通用類中的參數

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> 
{ 
} 

我想什麼是設置默認Bar上的Foo<TFoo>每個實現。 在代碼的其他部分,創建了TBar的實例,如果它是Bar<TFoo>,則該實例失敗,因爲這是abstract類。

但是,下面的錯誤被拋出,我不明白我能做什麼或者甚至有可能。

爲了泛型類使用它作爲參數「TBAR」類型「BarImpl」必須轉換爲「酒吧」「富」

我已經嘗試過讓BarImplBar<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>類型的對象intantiated(因爲它的abtract)。

+3

泛型和間接函數的級別可能太多。我讓我的頭腦旋轉,試圖追隨哪種類型繼承或實現,或者是基於還是遵循約束。有沒有可能簡化這個例子? –

+0

Foo不能創建它自己的Bar實例,但是它提供了(構造函數)還是繼承自FooImpl? – Terence

+0

@ LasseV.Karlsen我會很高興有這個簡化,因爲我的頭腦在旋轉,因爲這一天。任何想法將不勝感激。不知道我的問題是否清楚了我想要在這裏實現的目標... – KingKerosin

回答

1

我想你必須結束你的通用遞歸循環:

通用接口:

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>(); 

我還是不明白,你想在那裏這裏完成,有一個更好的解釋了什麼應該是更好的解決方案。

相關問題