2013-08-23 32 views
3

我不會只用一個方法拆箱這樣的:如何使用泛型?

public interface IModule<T, U> 
    where T : BaseBox 
    where U : BaseItem 
{ 
    U[] GetItems<T>(int id); 
} 

public sealed partial class Module<T, U> : IModule<T, U> 
    where T : BaseBox 
    where U : BaseItem 
{ 
    U[] IModule<T, U>.GetItems<T>(int id) 
    { 
    return T.Unboxing(); // It is wrong! 
    } 
} 

但我不能。我該如何編寫正確的泛型?

下一頁代碼understand.I品的類型:

public abstract class BaseItem 
{ 
    protected int _id; 
    protected string _description; 
} 

public sealed class TriangleItem : BaseItem 
{ 
    public int TriangleId { get { return _id; } set { _id = value; } } 
    public string TriangleDescription { get { return _description; } set { _description = value; } } 
    public Color color { get; set; } 
} 

public sealed class CircleItem : BaseItem 
{ 
    public int CircleId { get { return _id; } set { _id = value; } } 
    public string CircleDescription { get { return _description; } set { _description = value; } } 
    public int Radius { get; set; } 
} 

然後,我有盒項目:

public abstract class BaseBox 
{ 
    public string ItemsXml { get; set; } 
    public abstract BaseItem[] Unboxing(); 
} 

public sealed class TriangleBox : BaseBox 
{ 
    public TriangleItem[] Unboxing() 
    { 
    return Util.FromXml(ItemsXml).Select(i => new TriangleItem { TriangleId = int.Parse(i), TriangleDescription = i, Color = Color.Red }).ToArray(); 
    } 
} 

public sealed class CircleBox : BaseBox 
{ 
    public CircleItem[] Unboxing() 
    { 
    return Util.FromXml(ItemsXml).Select(i => new CircleItem { CircleId = int.Parse(i), CircleDescription = i, Radius = 5 }).ToArray(); 
    } 
} 

在這裏,我有不同的實現拆箱法。

+2

你已經寫了'T.Unboxing()'好像它是一個靜態方法,你需要一個實例使用 – Sayse

+0

你要麼需要問正確的'T'作爲參數,或者使用你的'int id'來獲取它。 – Nolonar

+0

我真的覺得你應該放棄泛型,並嘗試做純粹的面向對象設計。 C#中的泛型不像其他基於類的語言那樣強大,比如Haskell。濫用這種泛型只是在問問題。 – Euphoric

回答

3

由於Saysethe comment中提到,所以您試圖將T用作靜態方法並需要一個實例。例如,所有的

public sealed partial class Module<T, U> : IModule<T, U> 
    where T : BaseBox 
    where U : BaseItem 
{ 
    private T _box; 

    public Module(T box) 
    { 
     _box = box; 
    } 

    U[] IModule<T, U>.GetItems<T>(int id) 
    { 
     // You need to determine how id relates to _box. 
     return _box.Unboxing(); 
    } 
} 
+0

乾杯,沒有時間完全寫和檢查答案:) – Sayse

0

首先來到你的接口定義:

public interface IModule<T, U> 
    where T : BaseBox 
    where U : BaseItem 
{ 
    U[] GetItems<T>(int id); 
} 

您可以簡單地聲明GetItems<T>(int id)GetItems(int id)

您的代碼return T.Unboxing()是錯誤的,因爲T代表類型(例如類TriangleBoxCircleBox等),而不是你想打電話給你的方法的對象。 您可以通過將特定對象作爲參數GetItems或將BaseBox T作爲構造函數參數來解決此問題。即 要麼

U[] IModule<T, U>.GetItems(T box, int id) 
    { 
     return box.Unboxing(); // I don't know what you plan to do with id 
    } 

private readonly T _box; 
public Module(T box) 
    { 
     _box = box; 
    } 

U[] IModule<T, U>.GetItems(int id) 
    { 
     return _box.Unboxing(); // I don't know what you plan to do with id 
    }