C程序是一组函数和数据类型,C++程序是一组函数和类,C#程序是一组类型声明。
这三个编程语言—C、C++和C#—分别代表了不同的编程范式和设计思想,这也体现在它们的基本组成元素上。
C 程序
C语言主要是一种过程式编程语言。在C语言中,程序主要由函数和数据类型组成。函数用于执行操作,数据类型(包括结构体)用于定义数据的结构。
#include <stdio.h>
struct Point {
int x;
int y;
};
void printPoint(struct Point p) {
printf("Point: (%d, %d)\n", p.x, p.y);
}
int main() {
struct Point p = {1, 2};
printPoint(p);
return 0;
}
C++ 程序
C++是C语言的一个超集,它加入了面向对象编程的概念。因此,C++程序是由函数和类组成的。类不仅封装了数据,还封装了操作这些数据的方法。
#include <iostream>
class Point {
public:
int x;
int y;
void printPoint() {
std::cout << "Point: (" << x << ", " << y << ")" << std::endl;
}
};
int main() {
Point p;
p.x = 1;
p.y = 2;
p.printPoint();
return 0;
}
C# 程序
C#进一步发展了这些概念,将程序看作是一组类型声明。这些类型包括了值类型(如整型、枚举、结构体)和引用类型(如类、接口、委托、数组等),并且它们都是一等公民(First-Class Citizen)。
using System;
struct Point {
public int X;
public int Y;
}
enum Direction {
North,
South,
East,
West
}
interface IRunnable {
void Run();
}
class Person : IRunnable {
public string Name { get; set; }
public int Age { get; set; }
public void Run() {
Console.WriteLine(#34;{Name} is running.");
}
}
delegate void Notify(string message);
class Program {
static void Main(string[] args) {
Point p = new Point { X = 1, Y = 2 };
Direction d = Direction.North;
Person person = new Person { Name = "Alice", Age = 30 };
person.Run();
Notify notify = message => Console.WriteLine(message);
notify("Program started.");
}
}
在C#中,类型是一种用于封装数据和行为的全面方式。与C和C++相比,C#的类型系统更加一致和全面。这就是为什么说C#程序是一组类型声明的原因。这些类型声明不仅定义了数据的结构,还定义了数据的行为和数据之间的交互方式。这样的设计使得C#程序更加模块化和易于维护。