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

但我不能。我如何编写正确的泛型?

下一个要理解的代码。我有项目的类型:

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

这里我有不同的实现拆箱方法。

4

2 回答 2

3

正如评论中提到Sayse,您正在尝试将 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();
    }
}
于 2013-08-23T07:36:19.180 回答
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代表一种类型(例如 classesTriangleBoxCircleBox),而不是您想要调用您的方法的对象。您可以通过将特定对象作为参数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
    }
于 2013-08-23T07:40:55.610 回答