編集: サンプル コードを再構築して、より関連性の高いオブジェクトのセットを含めました。
解決策を見つけるのに苦労している興味深い状況があります。ジェネリックを使用する抽象関数を持つ抽象クラスがあります (以下のコード例を参照)。継承クラスで、関数をオーバーロードしようとしていますが、取得しています
エラー CS0030: 型 'Sample.Thingy' を 'T' に変換できません (CS0030)
当然、これは私の実際のコードではありませんが、このコードは私が得ているものと同じ結果を生成します。戻り値を (T) にキャストしようとすると、同様のエラーが発生します。where T : BaseThingy
またはを追加しようとするとwhere T : Thingy
、
エラー CS0460: 'Sample.Container.GetThingy(Guid)': オーバーライドおよび明示的なインターフェイス実装メソッドの制約を指定できません (CS0460)
namespace Sample {
// The abstract base class for thingies
public abstract class BaseThingy {
private Guid m_ID;
private String m_Name;
public BaseThingy( ) {
m_ID = Guid.NewGuid( );
}
public BaseThingy( Guid id ) {
m_ID = id;
}
public Guid ID {
get {
return m_ID;
}
}
public String Name {
get {
return m_Name;
}
set {
m_Name = value;
}
}
}
// The abstract base class for containers
public abstract class BaseContainer {
public abstract T GetThingy<T>(Guid id) where T : BaseThingy;
}
// Inherits from BaseThingy
public class RedThingy : BaseThingy {
private DateTime m_Created;
public RedThingy( ) : base( ) {
m_Created = DateTime.Now;
}
public RedThingy( Guid id ) : base( id ) {
m_Created = DateTime.Now;
}
public DateTime Created {
get {
return m_Created;
}
}
}
// Inherits from BaseThingy
public class BlueThingy : BaseThingy {
public BlueThingy( ) : base( ) {
}
public BlueThingy( Guid id ) : base( id ) {
}
}
// Inherits from BaseContainer
public class Container : BaseContainer {
private System.Collections.Generic.Dictionary<Guid, RedThingy> m_RedThingies;
private System.Collections.Generic.Dictionary<Guid, BlueThingy> m_BlueThingies;
public Container( ) {
m_Thingies = new System.Collections.Generic.Dictionary<Guid, BaseThingy>();
}
public override T GetThingy<T>( Guid id ) where T : BaseThingy {
if( typeof( T ) == typeof( RedThingy ) {
if( m_RedThingies.ContainsKey( id ) ) {
return m_RedThingies[ id ];
} else {
return null;
}
} else if( typeof( T ) == typeof( BlueThingy ) ) {
if( m_BlueThingies.ContainsKey( id ) ) {
return m_BlueThingies[ id ];
} else {
return null;
}
} else {
return null;
}
}
public void AddThing( RedThingy item ) {
if( item != null && !m_RedThingies.ContainsKey( item.ID ) ) {
m_RedThingies.Add( item.ID, item );
}
}
public void AddThing( BlueThingy item ) {
if( item != null && !m_BlueThingies.ContainsKey( item.ID ) ) {
m_BlueThingies.Add( item.ID, item );
}
}
}
}