C# 如何约束多个泛型类型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/401174/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to constrain multiple generic types?
提问by George Mauer
Here's a simple syntax question (I hope), I know how to constrain one generic type using the where clause, but how to constrain two generic types?
这是一个简单的语法问题(我希望如此),我知道如何使用 where 子句约束一个泛型类型,但是如何约束两个泛型类型?
Maybe the easiest way is to write down what my best guess as to the syntax was.
也许最简单的方法是写下我对语法的最佳猜测。
public class GenericDaoGetByIdTests<TDao, TComponent> : BaseDaoTests
where TDao : IDao<TComponent>, TComponent : EDC2ORMComponent {
public void GetByIdTest(int id) { }
}
This gives me an error. Anyone know what the proper syntax is?
这给了我一个错误。任何人都知道正确的语法是什么?
采纳答案by ChrisW
Use two 'where' keywords, for example I have a declaration like this:
使用两个“where”关键字,例如我有一个这样的声明:
public interface IParentNodeT<TChild, TSelf>
where TChild : IChildNodeT<TSelf, TChild>, INodeT<TChild>
where TSelf : IParentNodeT<TChild, TSelf>
{
TChild childRoot { get; set; }
}
回答by Raymond Roestenburg
This should work:
这应该有效:
public class GenericDaoGetByIdTests<TDao, TComponent> : BaseDaoTests
where TDao : IDao<TComponent> where TComponent : EDC2ORMComponent {
public void GetByIdTest(int id) { }
}
you just repeat the where.
你只是重复的地方。