已编辑:重构示例代码以包含一组更相关的对象。
我有一个有趣的情况,我很难找到解决方案。我有一个带有使用泛型的抽象函数的抽象类(请参见下面的示例代码)。在继承类中,我试图重载函数,但我得到了
错误 CS0030:无法将类型“Sample.Thingy”转换为“T”(CS0030)
当然,这不是我的真实代码,但这段代码产生的结果与我得到的结果相同。如果我尝试将返回值转换为 (T),我会收到类似的错误。如果我尝试添加where T : BaseThingy
or 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 );
}
}
}
}