如果我有一个看起来像这样的通用 Item 类:
abstract class Item<T>
{
}
还有一个看起来像这样的项目容器:
class Container<TItem, T>
where TItem : Item<T>
{
}
既然 TItem 依赖于 T,是否可以简化 Container 的类型签名,使其只接受一个类型参数?我真正想要的是这样的:
class Container<TItem>
where TItem : Item // this doesn't actually work, because Item takes a type parameter
{
}
所以我可以如下实例化它:
class StringItem : Item<string>
{
}
var good = new Container<StringItem>();
var bad = new Container<StringItem, string>();
当 TItem 是 StringItem 时,编译器应该能够推断出 T 是字符串,对吗?我该如何做到这一点?
期望的用法:
class MyItem : Item<string>
{
}
Container<MyItem> container = GetContainer();
MyItem item = container.GetItem(0);
item.MyMethod();
我认为这应该可以满足您的要求。显然你现在正在做 Container<string>
不是Container<StringItem>
但由于您没有包含使用示例,我认为这不是问题。
using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var myContainer = new Container<string>();
myContainer.MyItems = new List<Item<string>>();
}
}
public class Item<T> { }
public class Container<T>
{
// Just some property on your container to show you can use Item<T>
public List<Item<T>> MyItems { get; set; }
}
}
这个修改版怎么样:
using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var myContainer = new Container<StringItem>();
myContainer.StronglyTypedItem = new StringItem();
}
}
public class Item<T> { }
public class StringItem : Item<string> { }
// Probably a way to hide this, but can't figure it out now
// (needs to be public because it's a base type)
// Probably involves making a container (or 3rd class??)
// wrap a private container, not inherit it
public class PrivateContainer<TItem, T> where TItem : Item<T> { }
// Public interface
public class Container<T> : PrivateContainer<Item<T>, T>
{
// Just some property on your container to show you can use Item<T>
public T StronglyTypedItem { get; set; }
}
}