如何使用通用?

时间:2013-08-23 07:28:27

标签: c# generics

我不会像这样只使用一种解除方法:

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

这里我有不同的实现Unboxing-method。

2 个答案:

答案 0 :(得分:3)

Sayse中提到的the 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();
    }
}

答案 1 :(得分: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
    }