我想我终于明白了约束的意义,但还是有点困惑。有人可以告诉我以下内容是否正确吗?
基本上,如果您继承了一个类,您可能希望确保您继承的类也继承自其他类或其他接口(interface)。
这很令人困惑,因为你可能知道你只想从一个拥有你想要的东西的类继承,但我猜想使用泛型你可能会在某一时刻遇到编译错误,而不知道问题实际上源于事实上,某些类没有在其他地方继承,如果您在正确的区域添加约束,您可以获得有意义的错误。
这有意义吗?我走在正确的轨道上吗?
最佳答案
我不认为这是约束的重点,(但我可能是错的)。
据我了解,约束本身与继承关系不大。如果您正在使用(实例化)具有类型参数的类,您真正要做的是对可能使用的类型施加约束。
带有类型参数的类就像疯狂的库,而约束就像出现在空白下方的指令:
“鲍勃喜欢每天晚上和他的 friend 一起______。” (这是一个疯狂的人)
“Bob 喜欢每晚 _(动词)___ 和他的 friend 们”(带有说明的疯子)。
检查这个:
//class with type arguments
public class MadLib<W> {
public void addWord(W word) {
System.Console.WriteLine("bob likes to " + word + " with his friends");
}
}
//class with type arguments and contraints (note i'm not inheriting nothin)
public class MadLib<W> where W:Verb{
public void addWord(W word) {
System.Console.WriteLine("bob likes to " + word + " with his friends");
}
}
关于c# - 试图理解约束点——我走在正确的轨道上吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1412375/