C# 泛型 : Simplify type signature

标签 c# generics

<分区>

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

关于C# 泛型 : Simplify type signature,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16086708/

相关文章:

C++,要返回各种类实例如何创建模板?

c# - 带参数调用委托(delegate)方法名

c# - ListBox 和 Datasource - 防止第一项被选中

c# - 判断资源是否存在于 ResourceManager 中

c# - 循环泛型类型参数

C++ 泛型迭代器

java - java中带有extend的泛型方法

c# - 如何更改BeginConnect的超时

c# - 这个包含尖括号的符号是什么意思?

c# - 使用 Where 指定不同的泛型