在契约式设计中,类不变量必须在两种情况下满足:创建对象之后和调用例程之后。是否有任何示例或条件,我也必须在调用例程之前进行评估?
简而言之,我希望能够通过在所使用的所有类型中使用父类型,在数组中使用不同类型参数来存储泛型.MSDN提到这是不可能的,因为泛型是不变的类型,但是一条评论声明自4.0框架以来这种情况发生了变化.
这是我想要做的基本示例:
public class Animal
{
}
public class Dog : Animal
{
}
public class Cat : Animal
{
}
public class MyGeneric<T>
{ }
public class MyInheritedGeneric<T> : MyGeneric<T>
{ }
static void Main(string[] args)
{
MyGeneric<Animal>[] myGenericArray = new MyGeneric<Animal>[]
{
new MyGeneric<Dog>(),
new MyInheritedGeneric<Cat>()
};
}
Run Code Online (Sandbox Code Playgroud)
这会返回类似的错误:
Cannot implicitly convert type
'InheritanceTest.Program.MyGeneric<InheritanceTest.Program.Dog>' to
'InheritanceTest.Program.MyGeneric<InheritanceTest.Program.Animal>'
Cannot implicitly convert type
'InheritanceTest.Program.MyInheritedGeneric<InheritanceTest.Program.Cat>'
to 'InheritanceTest.Program.MyGeneric<InheritanceTest.Program.Animal>'
Run Code Online (Sandbox Code Playgroud)
有没有办法使用类型的父类将泛型存储在数组中,或者这根本不可能?我真的希望有可能,否则会让我的节目成为一场噩梦......
编辑:更多背景!
我正在制作课程以在游戏中产生敌人.我称之为模板(与实际的模板类无关,我很可能称之为蓝图或工厂).敌人构造函数接受一个模板,它用它来确定自己的值.当游戏加载时,模板用于生成所有敌人,使用他们的Generate()函数,该函数返回他们被分配生成的相应类型的数组.使用模板创建的所有对象都有一个构造函数,它将模板作为唯一参数.
public class Template<T>
{
protected static Random random = new Random();
protected …Run Code Online (Sandbox Code Playgroud) 我正在学习数据结构和算法的基础课程,我们使用的书是CLRS的开创性工作.我在理解循环不变量时遇到一些问题,如第2.1章:插入排序中所述.
这本书说:
在第1-8行的for循环的每次迭代开始时,子目标A [1..j -1]由最初在A [1..j-1]中的元素组成,但是按排序顺序.
现在,这让我很困惑.为什么在第一次迭代开始时它会成立?假设要排序的数组看起来像{5,2,4,6,1,3}.现在,当for循环的第一次迭代开始时,A [1 .. j-1]不是按排序顺序,但是当迭代结束时它就是.
我在这里错过了什么?
我试图找到循环的不变量(例如在下面的代码中)我真的不知道如何找到一般的不变量。任何人都可以帮助我如何找到不变量,并帮助我找到以下代码的不变量吗?谢谢
public static int div(int a, int b)
{
int q = 0;
while(a >= b)
{
a -= b;
q++;
}
return q;
}
Run Code Online (Sandbox Code Playgroud) 所以这是代码:
package week4
object expr {
abstract class Expr[T] {
def eval:T = this match {
case Number(x) => x
case Sum(e1, e2) => e1.eval + e2.eval
}
def show: String = this match {
case Number(x) => "" + x
case Sum(e1, e2) => "(" + e1.show + "+" + e2.show + ")"
}
}
case class Number[T](val value: T) extends Expr {
}
case class Sum[T](val e1: Expr[T], val e2: Expr[T]) extends Expr {
}
}
Run Code Online (Sandbox Code Playgroud)
除了我得到所有案例比较的错误:
构造函数无法实例化为期望的类型; …
An std::set是一种分类的关联容器,可快速查找其元素。密钥以一种有序的方式插入,一旦插入就不能修改密钥以保持该顺序。
考虑下面的示例,该示例构造一个std::set,int*然后尝试破坏其元素的排序:
#include <iostream>
#include <set>
int values[] = { 50, 40, 30, 20, 10 };
// Comparator that sorts by pointed value
struct comparator {
bool operator()(const int* left, const int* right) const {
return *left < *right;
}
};
using my_set_t = std::set<int*, comparator>;
// Checks if each of the elements of `values` are in the set
void output(const my_set_t & foo)
{
for (auto & x : values) {
std::cout << …Run Code Online (Sandbox Code Playgroud) 谁能解释一下编程语言中的不变量是什么以及它们为什么重要?