C#无界泛型类型作为约束

本文关键字:约束 泛型类型 | 更新日期: 2024-09-20 14:24:10

是否可能有一个无边界泛型类型的泛型约束?

例如:

public T DoSomething<T>(T dictionary) where T : IDictionary<,>
{
    ...
}

编辑:只是为了解释上下文,我想将方法的使用限制为IDictionary,但对于方法本身,TKey和TValue究竟是什么并不重要。

C#无界泛型类型作为约束

这是不可能的,您需要指定类型参数:

public T DoSomething<T, TKey, TValue>(T dictionary) where T : IDictionary<TKey, TValue> { ... }

不,你不能那样做。也许你可以使用

public IDictionary<TKey, TValue> DoSomething<TKey, TValue>(IDictionary<TKey, TValue> dictionary)
{
...
}

rosylin github中存在问题,但尚未解决。所以现在还不可能,但我预计很快就会实现。