16

如果我有一个看起来像这样的通用 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();
4

2 回答 2

2

我认为这应该做你想要的。显然你现在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; }
    }
}
于 2013-04-18T15:37:02.607 回答
1

我认为您的问题的一种可能的解决方案是添加接口IItem,代码结构将如下所示。

interface IItem { }

abstract class Item<T> : IItem { }

class Container<TItem> where TItem : IItem { }

class StringItem: Item<string> { }

现在你可以拥有Container<StringItem>

var container = new Container<StringItem>();
于 2013-04-18T15:59:14.407 回答