优秀的编程知识分享平台

网站首页 > 技术文章 正文

Java 和 C# 语法详细对比

nanyue 2025-03-03 19:33:21 技术文章 6 ℃

一、概述

Java 和 C# 都是面向对象的编程语言,它们有许多相似之处,都广泛应用于软件开发领域。Java 由 Sun Microsystems 开发,具有跨平台的特性,常用于企业级应用、Android 开发等;C# 是微软开发的编程语言,主要用于 Windows 平台的应用开发、游戏开发(如 Unity 引擎)等。下面从多个方面详细对比它们的语法。

二、基本语法结构

1. 程序入口

  • Java:Java 程序的入口是 main 方法,它必须是 public static void 类型,并且接受一个字符串数组作为参数。
public class Main {
    public static void main(String[] args) {
        System.out.println("Hello, Java!");
    }
}
  • C#:C# 程序的入口同样是 Main 方法,但它可以是 public 或 private,可以返回 void 或 int 类型,参数也可以是字符串数组或无参数。
using System;

class Program {
    static void Main(string[] args) {
        Console.WriteLine("Hello, C#!");
    }
}

2. 注释

  • Java:支持单行注释(//)、多行注释(/* ... */)和文档注释(/** ... */)。
// 这是单行注释
/*
这是多行注释
可以跨多行
*/
/**
 * 这是文档注释
 * 用于生成 API 文档
 */
public class CommentExample {
    // ...
}
  • C#:同样支持单行注释(//)、多行注释(/* ... */),还有 XML 注释(///)用于生成文档。
// 这是单行注释
/*
这是多行注释
可以跨多行
*/
/// 
/// 这是 XML 注释
/// 用于生成 API 文档
/// 
class CommentExample {
    // ...
}

三、数据类型

1. 基本数据类型

  • Java:有 8 种基本数据类型,分别是 byte、short、int、long、float、double、char 和 boolean。
byte b = 100;
short s = 2000;
int i = 100000;
long l = 10000000000L;
float f = 3.14f;
double d = 3.14159;
char c = 'A';
boolean bool = true;
  • C#:也有多种基本数据类型,如 byte、short、int、long、float、double、char、bool 等,部分类型名称相同但在某些细节上有差异。
byte b = 100;
short s = 2000;
int i = 100000;
long l = 10000000000L;
float f = 3.14f;
double d = 3.14159;
char c = 'A';
bool boolValue = true;

2. 引用数据类型

  • Java:所有类、接口、数组都是引用数据类型。对象的创建使用 new 关键字。
String str = new String("Hello");
int[] arr = new int[5];
  • C#:类、接口、数组也是引用数据类型,同样使用 new 关键字创建对象。
string str = new string("Hello");
int[] arr = new int[5];

四、面向对象编程

1. 类和对象

  • Java:类的定义使用 class 关键字,对象的创建使用 new 关键字。
class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public void sayHello() {
        System.out.println("Hello, my name is " + name + ", I'm " + age + " years old.");
    }
}

public class Main {
    public static void main(String[] args) {
        Person person = new Person("John", 25);
        person.sayHello();
    }
}
  • C#:类的定义同样使用 class 关键字,对象的创建也使用 new 关键字。
using System;

class Person {
    private string name;
    private int age;

    public Person(string name, int age) {
        this.name = name;
        this.age = age;
    }

    public void SayHello() {
        Console.WriteLine($"Hello, my name is {name}, I'm {age} years old.");
    }
}

class Program {
    static void Main() {
        Person person = new Person("John", 25);
        person.SayHello();
    }
}

2. 继承

  • Java:使用 extends 关键字实现类的继承,一个类只能继承一个父类。
class Animal {
    public void eat() {
        System.out.println("Animal is eating.");
    }
}

class Dog extends Animal {
    public void bark() {
        System.out.println("Dog is barking.");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.eat();
        dog.bark();
    }
}
  • C#:同样使用 : 符号实现类的继承,一个类也只能继承一个父类。
using System;

class Animal {
    public void Eat() {
        Console.WriteLine("Animal is eating.");
    }
}

class Dog : Animal {
    public void Bark() {
        Console.WriteLine("Dog is barking.");
    }
}

class Program {
    static void Main() {
        Dog dog = new Dog();
        dog.Eat();
        dog.Bark();
    }
}

3. 接口

  • Java:使用 interface 关键字定义接口,类使用 implements 关键字实现接口。
interface Shape {
    double getArea();
}

class Circle implements Shape {
    private double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    @Override
    public double getArea() {
        return Math.PI * radius * radius;
    }
}

public class Main {
    public static void main(String[] args) {
        Circle circle = new Circle(5);
        System.out.println("Circle area: " + circle.getArea());
    }
}
  • C#:使用 interface 关键字定义接口,类使用 : 符号实现接口。
using System;

interface Shape {
    double GetArea();
}

class Circle : Shape {
    private double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    public double GetArea() {
        return Math.PI * radius * radius;
    }
}

class Program {
    static void Main() {
        Circle circle = new Circle(5);
        Console.WriteLine($"Circle area: {circle.GetArea()}");
    }
}

五、异常处理

1. 异常捕获

  • Java:使用 try-catch-finally 语句捕获和处理异常。
public class ExceptionExample {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;
        } catch (ArithmeticException e) {
            System.out.println("Error: " + e.getMessage());
        } finally {
            System.out.println("This is the finally block.");
        }
    }
}
  • C#:同样使用 try-catch-finally 语句捕获和处理异常。
using System;

class ExceptionExample {
    static void Main() {
        try {
            int result = 10 / 0;
        } catch (DivideByZeroException e) {
            Console.WriteLine($"Error: {e.Message}");
        } finally {
            Console.WriteLine("This is the finally block.");
        }
    }
}

2. 异常抛出

  • Java:使用 throw 关键字抛出异常,使用 throws 关键字声明方法可能抛出的异常。
class CustomException extends Exception {
    public CustomException(String message) {
        super(message);
    }
}

public class ExceptionThrowExample {
    public static void test() throws CustomException {
        throw new CustomException("This is a custom exception.");
    }

    public static void main(String[] args) {
        try {
            test();
        } catch (CustomException e) {
            System.out.println("Caught exception: " + e.getMessage());
        }
    }
}
  • C#:使用 throw 关键字抛出异常,方法可以不声明可能抛出的异常。
using System;

class CustomException : Exception {
    public CustomException(string message) : base(message) { }
}

class ExceptionThrowExample {
    static void Test() {
        throw new CustomException("This is a custom exception.");
    }

    static void Main() {
        try {
            Test();
        } catch (CustomException e) {
            Console.WriteLine($"Caught exception: {e.Message}");
        }
    }
}

六、泛型

1. 泛型类

  • Java:使用 <> 符号定义泛型类。
class GenericClass {
    private T value;

    public GenericClass(T value) {
        this.value = value;
    }

    public T getValue() {
        return value;
    }
}

public class Main {
    public static void main(String[] args) {
        GenericClass generic = new GenericClass<>(10);
        System.out.println("Value: " + generic.getValue());
    }
}
  • C#:同样使用 <> 符号定义泛型类。
using System;

class GenericClass {
    private T value;

    public GenericClass(T value) {
        this.value = value;
    }

    public T GetValue() {
        return value;
    }
}

class Program {
    static void Main() {
        GenericClass generic = new GenericClass(10);
        Console.WriteLine($"Value: {generic.GetValue()}");
    }
}

2. 泛型方法

  • Java:在方法返回类型前使用 <> 符号定义泛型方法。
public class GenericMethodExample {
    public static  void printArray(T[] array) {
        for (T element : array) {
            System.out.print(element + " ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        Integer[] intArray = {1, 2, 3, 4, 5};
        printArray(intArray);
    }
}
  • C#:在方法返回类型前使用 <> 符号定义泛型方法。
using System;

class GenericMethodExample {
    public static void PrintArray(T[] array) {
        foreach (T element in array) {
            Console.Write(element + " ");
        }
        Console.WriteLine();
    }

    static void Main() {
        int[] intArray = { 1, 2, 3, 4, 5 };
        PrintArray(intArray);
    }
}

七、委托和事件(C# 特有)

在 Java 中没有直接对应的委托和事件机制,通常使用接口和内部类来实现类似的功能;而 C# 有内置的委托和事件机制。

1. 委托

using System;

// 定义委托
delegate void MyDelegate(string message);

class Program {
    static void PrintMessage(string message) {
        Console.WriteLine(message);
    }

    static void Main() {
        // 创建委托实例
        MyDelegate del = PrintMessage;
        // 调用委托
        del("Hello, C#!");
    }
}

2. 事件

using System;

// 定义委托
delegate void EventHandler(string message);

class EventPublisher {
    // 定义事件
    public event EventHandler MyEvent;

    public void RaiseEvent() {
        if (MyEvent != null) {
            MyEvent("Event is raised!");
        }
    }
}

class EventSubscriber {
    public void HandleEvent(string message) {
        Console.WriteLine(message);
    }
}

class Program {
    static void Main() {
        EventPublisher publisher = new EventPublisher();
        EventSubscriber subscriber = new EventSubscriber();

        // 订阅事件
        publisher.MyEvent += subscriber.HandleEvent;

        // 触发事件
        publisher.RaiseEvent();
    }
}

八、Lambda 表达式

1. Java

import java.util.Arrays;
import java.util.List;

public class LambdaExample {
    public static void main(String[] args) {
        List numbers = Arrays.asList(1, 2, 3, 4, 5);
        numbers.forEach(n -> System.out.print(n + " "));
    }
}

2. C#

using System;
using System.Collections.Generic;

class LambdaExample {
    static void Main() {
        List numbers = new List { 1, 2, 3, 4, 5 };
        numbers.ForEach(n => Console.Write(n + " "));
    }
}

九、总结

Java 和 C# 在语法上有很多相似之处,都遵循面向对象编程的原则,具有基本的数据类型、类、继承、接口等特性。但它们也有一些差异,如 C# 有委托和事件机制,而 Java 没有直接对应的功能;Java 的跨平台特性更强,而 C# 更适合 Windows 平台的开发。开发者可以根据具体的项目需求和平台选择合适的编程语言。

最近发表
标签列表