如果我有一个如下所示的通用 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>
not 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; }
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)