我看过其他类似的问题,但问题是语法错误。也许我遗漏了一些东西,但据我所知,我的语法看起来是正确的。 我正在尝试声明一个方法,如下所示:
internal IDictionary<string, T> FillObjects(
IReadableRange<T> svc,
Func<T, string> getKey) where T : BaseEntity
{
}
但是我得到了编译器错误:
constraints are not allowed on non-generic declarations
有什么想法吗?
谢谢
马特
最佳答案
问题是你的方法没有定义泛型类型 <T>
.它只使用类型 T
由封闭类型给出。
并且您只能在 the same place where you define generic parameters 处声明约束.
有两种解决方法:
1.,您应该在函数上定义泛型参数:
public class EnclosingType
{
internal IDictionary<string, T> FillObjects<T>(
IReadableRange<T> svc,
Func<T, string> getKey) where T : BaseEntity
{
}
}
在你的情况下它不会编译,因为你 EnclosingType
可能是 EnclosingType<T>
这导致 EnclosingType's
之间的歧义T
和 FillObjects'
T
:
2.,或者您可以只定义封闭类型的约束:
public class EnclosingType<T>
where T : BaseEntity
{
internal IDictionary<string, T> FillObjects(
IReadableRange<T> svc,
Func<T, string> getKey)
{
}
}
关于c# - 非通用声明不允许约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25441374/