问题描述
我一直在网上寻找声明式和命令式编程的定义,这将为我提供一些启发.但是,在我发现的某些资源中使用的语言令人生畏-例如在 Wikipedia .有没有人有一个真实的例子可以向我展示这个主题,也许可以带给我一些观点(也许在C#中)?
I have been searching the web looking for a definition for declarative and imperative programming that would shed some light for me. However, the language used at some of the resources that I have found is daunting - for instance at Wikipedia.Does anyone have a real-world example that they could show me that might bring some perspective to this subject (perhaps in C#)?
推荐答案
LINQ是一个很好的C#声明式与命令式编程示例.
A great C# example of declarative vs. imperative programming is LINQ.
通过命令式编程,您可以逐步告诉编译器您要发生的事情.
With imperative programming, you tell the compiler what you want to happen, step by step.
例如,让我们从这个集合开始,然后选择奇数:
For example, let's start with this collection, and choose the odd numbers:
List<int> collection = new List<int> { 1, 2, 3, 4, 5 };
使用命令式编程,我们将逐步完成并确定所需的内容:
With imperative programming, we'd step through this, and decide what we want:
List<int> results = new List<int>();
foreach(var num in collection)
{
if (num % 2 != 0)
results.Add(num);
}
在这里,我们是说:
- 创建结果集合
- 逐步浏览集合中的每个数字
- 检查数字,如果是奇数,则将其添加到结果中
另一方面,使用声明性编程,您可以编写描述所需内容的代码,而不必描述如何获取(说明所需的结果,但不能逐步说明) :
With declarative programming, on the other hand, you write code that describes what you want, but not necessarily how to get it (declare your desired results, but not the step-by-step):
var results = collection.Where( num => num % 2 != 0);
在这里,我们说的是给我们所有奇怪的地方",而不是逐步检查集合.请检查此项目,如果它很奇怪,请将其添加到结果集合中."
Here, we're saying "Give us everything where it's odd", not "Step through the collection. Check this item, if it's odd, add it to a result collection."
在许多情况下,代码也将是两种设计的混合体,因此它并不总是黑白的.
In many cases, code will be a mixture of both designs, too, so it's not always black-and-white.
这篇关于声明式和命令式编程之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!