如何使用泛型

本文关键字:泛型 何使用 | 更新日期: 2023-09-27 18:28:54

我习惯于只使用一种方法来打开这样的盒子:

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方法。

如何使用泛型

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

首先介绍您的接口定义:

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
    }