我想轉換字典,以便將值轉換爲由原始類型實現的接口;c#如何投用通用類型
首先:
public class DataRef<T> : IRef
{
public int ID;
public static Dictionary<int, T> LookUp = new Dictionary<int, T>();
}
public class Terrain : IThing
{
///IThing
public ImageRef DefaultImageRef { get { return defaultImageRef; } }
public string Name { get { return name; } }
public string name = "unamed Terrain";
//Other Stuff
public TerrainType TerrainType = TerrainType.Floor;
public ImageRef defaultImageRef = new ImageRef(typeof(Terrain));
public ImageRef alternateImageRef = new ImageRef(typeof(Terrain));
public int imageRef2;
}
public interface IThing
{
ImageRef DefaultImageRef { get; }
string Name { get; }
}
這種表達不能編譯:
(Dictionary<int,IThing>)DataRef<Terrain>.LookUp
錯誤:
Error 15 Cannot convert type 'System.Collections.Generic.Dictionary< int,MO1.Definitions.Terrain >' to 'System.Collections.Generic.Dictionary< int,MO1.Definitions.IThing >' C:\Projects\MO1RPG\VSsolution\Editor\Main.cs 28 72 Editor
我想投的字典,因爲我想用它作爲一個參數被轉換爲「Dictionary」有沒有辦法做到這一點?