我不会只使用一种方法来像这样解箱:
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。
发布于 2013-08-23 15:36:19
正如the comment中提到的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-23 15:40:56
首先来看看你的接口定义:
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表示一个类型(例如,TriangleBox,CircleBox等类)而不是要对其调用方法的对象。您可以通过将特定对象作为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
}https://stackoverflow.com/questions/18397205
复制相似问题