目录
1. 基础语法
// C#:以分号结尾,大括号包裹代码块
if (condition) {
Console.WriteLine("Hello");
}
// Java:语法与C#类似,但包声明强制
package com.example;
public class Main {
public static void main(String[] args) {
if (condition) {
System.out.println("Hello");
}
}
}
# Python:缩进代替大括号,冒号结尾
if condition:
print("Hello")
2. 变量声明与类型推断
// C#:明确类型或var推断
int num = 10;
var name = "C#";
// Java:明确类型或var(Java 10+)
int num = 10;
var name = "Java";
# Python:动态类型,无需声明
num = 10
name = "Python"
3. 字符串插值
// C#:$前缀
string msg = $"Value: {num}";
// Java:String.format或+
String msg = String.format("Value: %d", num);
# Python:f字符串
msg = f"Value: {num}"
4. 数组初始化
// C#:类型后加[]
int[] arr = {1, 2, 3};
// Java:new关键字
int[] arr = new int[]{1, 2, 3};
# Python:列表动态类型
arr = [1, 2, 3]
5. 集合类
// C#:泛型集合
List<int> list = new List<int> {1, 2, 3};
// Java:需指定泛型类型
List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3));
# Python:直接使用列表
my_list = [1, 2, 3]
6. 类与构造函数
// C#:构造函数与属性初始化
public class Person {
public string Name { get; set; }
public Person(string name) => Name = name;
}
// Java:显式getter/setter
public class Person {
private String name;
public Person(String name) { this.name = name; }
public String getName() { return name; }
}
# Python:__init__方法
class Person:
def __init__(self, name):
self.name = name
7. 继承语法
// C#::符号
class Student : Person { }
// Java:extends关键字
class Student extends Person { }
# Python:括号内指定基类
class Student(Person):
pass
8. 接口实现
// C#:interface关键字
public interface ILogger {
void Log(string message);
}
class Logger : ILogger {
public void Log(string message) { }
}
// Java:interface与implements
interface Logger {
void log(String message);
}
class FileLogger implements Logger {
public void log(String message) { }
}
# Python:无原生接口,通过抽象类模拟
from abc import ABC, abstractmethod
class Logger(ABC):
@abstractmethod
def log(self, message):
pass
9. 异常处理
// C#:catch块类型过滤
try { }
catch (IOException ex) { }
finally { }
// Java:类似C#,但异常需声明
public void read() throws IOException {
try { }
catch (IOException e) { }
}
# Python:except捕获所有异常
try:
pass
except IOError as e:
pass
finally:
pass
10. Lambda表达式
// C#:箭头语法
Func<int, int> square = x => x * x;
// Java:函数式接口
Function<Integer, Integer> square = x -> x * x;
# Python:lambda关键字
square = lambda x: x * x
11-20. 中级特性对比
11. 异步编程
// C#:async/await
async Task<int> FetchAsync() {
await Task.Delay(1000);
return 42;
}
// Java:CompletableFuture
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 42);
# Python:asyncio
async def fetch():
await asyncio.sleep(1)
return 42
12. 属性访问
// C#:自动属性
public int Age { get; private set; }
// Java:需手动实现getter/setter
private int age;
public int getAge() { return age; }
private void setAge(int age) { this.age = age; }
# Python:直接访问或@property装饰器
@property
def age(self):
return self._age
13. 枚举定义
// C#:强类型枚举
public enum Color { Red, Green, Blue }
// Java:枚举类
public enum Color { RED, GREEN, BLUE }
# Python:Enum类
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
14. 泛型方法
// C#:类型参数
T Max<T>(T a, T b) where T : IComparable<T> {
return a.CompareTo(b) > 0 ? a : b;
}
// Java:类型擦除
<T extends Comparable<T>> T max(T a, T b) {
return a.compareTo(b) > 0 ? a : b;
}
# Python:动态类型无泛型,用类型提示
from typing import TypeVar
T = TypeVar('T')
def max(a: T, b: T) -> T:
return a if a > b else b
15. 扩展方法
// C#:静态类+this关键字
public static class StringExtensions {
public static bool IsEmpty(this string s) => string.IsNullOrEmpty(s);
}
// Java:无法添加扩展方法,需工具类
public class StringUtils {
public static boolean isEmpty(String s) { return s == null || s.isEmpty(); }
}
# Python:Monkey patching
def is_empty(s):
return not s
str.is_empty = is_empty
16. 文件操作
// C#:StreamReader
using (var reader = new StreamReader("file.txt")) {
string content = reader.ReadToEnd();
}
// Java:BufferedReader
try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {
String content = reader.lines().collect(Collectors.joining());
}
# Python:with语句
with open("file.txt", "r") as f:
content = f.read()
17. 空值处理
// C#:可空类型
int? num = null;
string s = null ?? "default";
// Java:Optional类
Optional<String> name = Optional.ofNullable(null);
String s = name.orElse("default");
# Python:None检查
s = None or "default"
18. 日期时间
// C#:DateTime
DateTime now = DateTime.Now;
// Java:LocalDateTime
LocalDateTime now = LocalDateTime.now();
# Python:datetime模块
from datetime import datetime
now = datetime.now()
19. JSON序列化
// C#:System.Text.Json
var obj = JsonSerializer.Deserialize<Person>(jsonString);
// Java:Gson库
Person obj = new Gson().fromJson(jsonString, Person.class);
# Python:json模块
import json
obj = json.loads(json_string)
20. 正则表达式
// C#:Regex类
var match = Regex.Match(input, @"\d+");
// Java:Pattern类
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(input);
# Python:re模块
import re
match = re.search(r'\d+', input)
21-30. 高级特性对比
21. 反射
// C#:Type类
Type type = typeof(Person);
object obj = Activator.CreateInstance(type);
// Java:Class类
Class<?> clazz = Class.forName("com.example.Person");
Object obj = clazz.newInstance();
# Python:__class__属性
obj = Person()
clazz = obj.__class__
new_obj = clazz.__new__(clazz)
22. 多线程
// C#:Task并行
Task.Run(() => Console.WriteLine("Thread"));
// Java:ExecutorService
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(() -> System.out.println("Thread"));
# Python:threading模块
import threading
threading.Thread(target=lambda: print("Thread")).start()
23. 依赖注入
// C#:ASP.NET Core DI
services.AddScoped<ILogger, FileLogger>();
// Java:Spring框架
@Bean
public ILogger logger() { return new FileLogger(); }
# Python:第三方库(如injector)
from injector import inject, Module, provider
class AppModule(Module):
@provider
def provide_logger(self) -> ILogger:
return FileLogger()
24. 单元测试
// C#:xUnit
[Fact]
public void Test1() => Assert.Equal(4, 2 + 2);
// Java:JUnit
@Test
public void test1() { assertEquals(4, 2 + 2); }
# Python:pytest
def test_add():
assert 2 + 2 == 4
25. 数据库访问
// C#:Entity Framework
var users = context.Users.Where(u => u.Age > 18).ToList();
// Java:Hibernate
List<User> users = session.createQuery("FROM User WHERE age > 18").list();
# Python:SQLAlchemy
users = session.query(User).filter(User.age > 18).all()
总结
通过25处代码级对比可见:
- C#:语法现代,性能优异,适合Windows生态与企业级应用;
- Java:强类型与跨平台平衡,安卓与后端开发主流;
- Python:动态灵活,数据科学与脚本领域不可替代。
选择语言时需结合项目需求、团队技能、生态支持综合评估。