java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java快速转C#

Java快速转C#的简明教程

作者:zimoyin

最近正在研究将一个纯java工程如何转换成C#工程,代码量还比较大,这里记录一番,这篇文章主要介绍了Java快速转C#的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考下

以下是一个针对 Java 开发者快速转向 C# 的简明教程,重点对比 Java 与 C# 的异同,帮助你快速上手。

项目结构:

一、基础语法对比

1.变量与数据类型

JavaC#
int a = 10;int a = 10;
String name = "Hello";string name = "Hello";
final int MAX = 100;const int MAX = 100;
var list = new ArrayList<>(); (Java 10+)var list = new List<string>();

C# 特色:

2.拓展方法

C# 的扩展方法允许你为现有类型 (包括密封类、接口、甚至第三方库的类型)“添加”方法,而无需修改其源代码或继承。这是 C# 特有的语法特性,Java 中无直接等价物(需通过工具类或继承实现)。

定义扩展方法

// 静态类:扩展方法容器
public static class StringExtensions {
    // 扩展 string 类型的方法
    public static bool IsNullOrEmpty(this string str) {
        return string.IsNullOrEmpty(str);
    }
}

使用拓展方法

string name = null;

// 调用扩展方法(如同实例方法)
if (name.IsNullOrEmpty()) {
    Console.WriteLine("Name is null or empty");
}

值得注意的是,拓展方法作为一个语法糖对应的可以解决在Java中 xxUtils 的工具类。同时具有以下注意:

3.空运算符(Null Handling Operators)

C# 提供了强大的空值处理运算符,简化空值检查逻辑,避免 NullReferenceException

1. 空条件运算符(?.)

用于安全访问对象的成员,若对象为 null 则返回 null 而非抛出异常。

Person person = GetPerson(); // 可能为 null

// 安全访问属性和方法
int length = person?.Name?.Length ?? 0;
person?.SayHello();

对比 Java

2. 空合并运算符(??)

提供默认值,当左侧表达式为 null 时返回右侧值。

string name = null;
string displayName = name ?? "Guest"; // 如果 name 为 null,则使用 "Guest"

对比 Java

3. 空合并赋值运算符(??=)

仅当变量为 null 时才赋值(C# 8.0+)。

string message = GetMessage();
message ??= "Default Message"; // 如果 GetMessage() 返回 null,则赋值为默认值

对比 Java

4. 非空断言运算符(!)

告知编译器某个表达式不为 null(C# 8.0+,用于可空引用类型上下文)。

string name = GetName()!; // 告诉编译器 GetName() 返回值不为 null

注意事项

二、面向对象编程

1.类与对象

public class Person {
    // 字段
    private string name;

    // 属性(推荐封装字段)
    public string Name {
        get { return name; }
        set { name = value; }
    }

    // 构造函数
    public Person(string name) {
        this.name = name;
    }

    // 方法
    public void SayHello() {
        Console.WriteLine($"Hello, {name}");
    }
}

对比 Java:

2.继承与接口

// 继承
public class Student : Person {
    public Student(string name) : base(name) {}
}

// 接口
public interface IRunnable {
    void Run();
}

public class Car : IRunnable {
    public void Run() {
        Console.WriteLine("Car is running");
    }
}

对比 Java:

三、C# 特有特性

1.委托与事件(Delegates & Events)

// 委托(类似 Java 的函数式接口)
// 定义一个名为 Notify 的委托类型,它表示一种方法模板,要求方法返回 void 并接受一个 string 参数
// 类比 Java :类似 Java 中的函数式接口(如 Consumer<String>),但 C# 的委托更直接,可以直接绑定方法。
public delegate void Notify(string message);

// 事件
public class EventPublisher {
	// 声明一个事件 OnNotify,其类型是 Notify 委托。事件本质上是委托的安全封装,外部只能通过 +=/-= 订阅/取消订阅,不能直接调用(如 OnNotify.Invoke() 会报错)。
    public event Notify OnNotify;

	// 调用 OnNotify?.Invoke(...) 触发事件,?. 是空值保护操作符(避免空引用异常)。只有当至少有一个订阅者时,才会执行。
    public void TriggerEvent() {
        OnNotify?.Invoke("Event triggered!");
    }
}

// 使用
EventPublisher publisher = new EventPublisher();
publisher.OnNotify += (msg) => Console.WriteLine(msg);
publisher.TriggerEvent();

2.LINQ(Language Integrated Query)

var numbers = new List<int> { 1, 2, 3, 4, 5 };
var even = numbers.Where(n => n % 2 == 0).ToList();

对比 Java:

3.异步编程(Async/Await)

public async Task DownloadDataAsync() {
    var client = new HttpClient();
    var data = await client.GetStringAsync("https://example.com");
    Console.WriteLine(data);
}

对比 Java:

Parallel.Invoke(() => {
   // 并行执行CPU密集任务
});

四、常用工具与框架

JavaC#
Maven/GradleNuGet(包管理)
Spring.NET Core(框架)
JUnitxUnit/NUnit(测试框架)
IntelliJ IDEAVisual Studio / IntelliJ Rider(IDE)

五、项目结构与命名空间

// 文件:Program.cs
using System;
namespace MyApplication;

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

对比 Java:

六、Java 到 C# 的常见转换技巧

JavaC#
System.out.println()Console.WriteLine()
ArrayList<T>List<T>
HashMap<K,V>Dictionary<K,V>
interfaceinterface
enumenum
try-catch-finallytry-catch-finally

C# 中,反射(Reflection) 是一种强大的机制,允许在运行时动态地获取类型信息、创建对象实例、调用方法、访问字段和属性等。对于从 Java 转向 C# 的开发者来说,反射的概念是相似的,但 C# 的反射 API 更加简洁、直观,并且与语言特性(如 dynamicnameofLINQ)结合更紧密。

七、反射

反射是指在 运行时(runtime) 动态地:

Java 与 C# 反射的对比

功能JavaC#
获取类型对象MyClass.classobj.getClass()typeof(MyClass)obj.GetType()
获取方法clazz.getMethod("name", params...)type.GetMethod("Name")
调用方法method.invoke(obj, args)method.Invoke(obj, args)
获取属性clazz.getDeclaredField("name")type.GetProperty("Name")
获取程序集无直接等价物Assembly.GetExecutingAssembly()
动态创建实例clazz.newInstance()Activator.CreateInstance(type)
动态访问成员通过 Field/Method 对象通过 PropertyInfo/MethodInfo

1. 获取Type对象

// 通过类型名获取
Type type = typeof(string);

// 通过对象获取
object obj = new Person();
Type type = obj.GetType();

2. 获取类成员信息(属性、方法、字段)

Type type = typeof(Person);

// 获取所有属性
PropertyInfo[] properties = type.GetProperties();

// 获取特定方法
MethodInfo method = type.GetMethod("SayHello");

// 获取所有字段
FieldInfo[] fields = type.GetFields();

3. 动态创建实例

object person = Activator.CreateInstance(typeof(Person));

4. 调用方法

MethodInfo method = type.GetMethod("SayHello");
method.Invoke(person, null);

5. 访问属性

PropertyInfo prop = type.GetProperty("Name");
prop.SetValue(person, "Alice");
string name = (string)prop.GetValue(person);

6. 访问字段(不推荐,除非必要)

FieldInfo field = type.GetField("age", BindingFlags.NonPublic | BindingFlags.Instance);
field.SetValue(person, 30);
int age = (int)field.GetValue(person);

7. 获取程序集信息

Assembly assembly = Assembly.GetExecutingAssembly();
foreach (Type type in assembly.GetTypes()) {
    Console.WriteLine(type.Name);
}

8. 动态加载 DLL 并调用方法

Assembly assembly = Assembly.LoadFile("path/to/MyLibrary.dll");
Type type = assembly.GetType("MyNamespace.MyClass");
object instance = Activator.CreateInstance(type);
MethodInfo method = type.GetMethod("DoSomething");
method.Invoke(instance, null);

9. 使用dynamic替代部分反射操作

dynamic person = new ExpandoObject();
person.Name = "Bob";
person.SayHello = new Action(() => Console.WriteLine("Hello"));
person.SayHello(); // 无需反射即可调用

10. 使用Expression构建高性能的反射调用

Func<object> factory = Expression.Lambda<Func<object>>(
    Expression.New(typeof(Person))
).Compile();
object person = factory();

11. 使用IL Emit或Source Generator优化性能

对于高性能场景(如 ORM、序列化框架),可以使用:

性能问题

解决方案

安全性

Java 到 C# 反射的转换技巧

JavaC#
Class.forName("MyClass")Type.GetType("MyNamespace.MyClass")
clazz.newInstance()Activator.CreateInstance(type)
method.invoke(obj, args)method.Invoke(obj, args)
clazz.getDeclaredMethods()type.GetMethods()
clazz.getDeclaredFields()type.GetFields()
clazz.getDeclaredField("name")type.GetField("Name")
clazz.getDeclaredMethod("name", params...)type.GetMethod("Name", parameterTypes)
clazz.getInterfaces()type.GetInterfaces()

八、引入包(NuGet 包管理)

在 C# 中,NuGet 是官方推荐的包管理系统,类似于 Java 中的 Maven/Gradle。它用于管理项目依赖项(如第三方库、框架等)。

NuGet 包典型命名规则:[组织名].[功能模块].[平台/框架]

1.NuGet 的作用

2.常用方式

方法 1:通过 Visual Studio 引入

  1. 右键项目 → Manage NuGet Packages
  2. Browse 标签页搜索包名(如 Newtonsoft.Json
  3. 点击 Install 安装包
  4. 安装完成后,会自动添加到项目中

方法 2:通过 CLI 命令行

# 安装包
dotnet add package Newtonsoft.Json

# 更新包
dotnet add package Newtonsoft.Json --version 13.0.1

# 卸载包
dotnet remove package Newtonsoft.Json

方法 3:手动编辑.csproj文件

在项目文件中添加 <PackageReference>

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
  </ItemGroup>
</Project>

3.NuGet 源配置

默认源是 nuget.org,但也可以配置私有源(如公司内部源):

# 添加私有源
dotnet nuget add source https://mycompany.com/nuget -n MyCompany

4.对比 Java

功能Java (Maven/Gradle)C# (NuGet)
包管理pom.xml / build.gradle.csproj
安装包mvn install / gradle builddotnet add package
私有仓库settings.xml / repositories { maven { url "..." } }dotnet nuget add source

九、引用本地的 DLL

有时你需要引用本地的 DLL 文件(如团队内部开发的库、第三方未提供 NuGet 包的库),可以通过以下方式实现。

1.添加本地 DLL 引用

方法 1:通过 Visual Studio 添加

  1. 右键项目 → Add → Reference…
  2. 在弹出窗口中选择 Browse
  3. 浏览并选择本地 DLL 文件(如 MyLibrary.dll
  4. 点击 AddOK

方法 2:手动编辑.csproj文件

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <Reference Include="MyLibrary">
      <HintPath>..\Libraries\MyLibrary.dll</HintPath>
    </Reference>
  </ItemGroup>
</Project>

2.确保 DLL 被正确复制到输出目录

.csproj 中添加以下配置,确保 DLL 被复制到 bin 目录:

<ContentWithTargetPath Include="..\Libraries\MyLibrary.dll">
  <TargetPath>MyLibrary.dll</TargetPath>
  <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</ContentWithTargetPath>

3.加载本地 DLL 的运行时行为

4.注意事项

常见问题与解决方案

1.无法找到 DLL

2.加载 DLL 失败

3.版本冲突

十、DllImport(平台调用,P/Invoke)

在 C# 中,[DllImport("xxx.dll")]平台调用(Platform Invocation Services,P/Invoke) 的核心特性,用于直接调用 非托管代码(如 Windows API、C/C++ 编写的 DLL)。这是 Java 中没有的特性(Java 需要通过 JNI 调用本地代码)。

1.基本概念

[DllImport]System.Runtime.InteropServices 命名空间下的特性(Attribute),用于声明某个方法的实现来自外部 DLL。它允许你在 C# 中直接调用 Windows API 或其他非托管函数。

2.使用步骤

步骤 1:引入命名空间

using System.Runtime.InteropServices;

步骤 2:声明外部方法

使用 [DllImport("dll名称")] 特性修饰方法,指定 DLL 名称和调用约定(Calling Convention)。

[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type);

步骤 3:调用方法

MessageBox(IntPtr.Zero, "Hello from C#", "Greeting", 0);

3.参数说明

参数说明
dllNameDLL 文件名(如 "user32.dll"
CharSet字符集(CharSet.AnsiCharSet.UnicodeCharSet.Auto
CallingConvention调用约定(默认为 CallingConvention.Winapi,也可指定 ThisCallStdCall 等)
EntryPoint可选,指定 DLL 中函数的入口点(当方法名与 DLL 函数名不同时使用)

4.常见示例

示例 1:调用user32.dll的MessageBox

[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int MessageBox(IntPtr hWnd, string text, string caption, uint type);

// 调用
MessageBox(IntPtr.Zero, "Hello from C#", "Greeting", 0);

示例 2:调用kernel32.dll的GetTickCount

[DllImport("kernel32.dll")]
public static extern uint GetTickCount();

// 调用
uint tickCount = GetTickCount();
Console.WriteLine($"System uptime: {tickCount} ms");

示例 3:调用gdi32.dll的CreateDC

[DllImport("gdi32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr CreateDC(string lpszDriver, string lpszDevice, string lpszOutput, IntPtr lpInitData);

// 调用
IntPtr hdc = CreateDC("DISPLAY", null, null, IntPtr.Zero);

5.结构体与指针传参

当调用的函数需要结构体或指针参数时,需使用 refoutIntPtr,并可能需要使用 StructLayoutMarshalAs 来控制内存布局。

示例:调用user32.dll的GetWindowRect

[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
    public int Left;
    public int Top;
    public int Right;
    public int Bottom;
}

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);

// 使用
RECT rect;
bool success = GetWindowRect(hWnd, out rect);
if (success)
{
    Console.WriteLine($"Window Rect: {rect.Left}, {rect.Top}, {rect.Right}, {rect.Bottom}");
}

6.注意事项

安全性

平台依赖性

性能

参数封送(Marshaling)

7. 示例:封装一个 Windows API 工具类

using System;
using System.Runtime.InteropServices;

public static class Win32Api
{
    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    public static extern int MessageBox(IntPtr hWnd, string text, string caption, uint type);

    [DllImport("kernel32.dll")]
    public static extern uint GetTickCount();

    [StructLayout(LayoutKind.Sequential)]
    public struct RECT
    {
        public int Left;
        public int Top;
        public int Right;
        public int Bottom;
    }

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
}

// 使用
class Program
{
    static void Main()
    {
        // 调用 MessageBox
        Win32Api.MessageBox(IntPtr.Zero, "Hello from C#", "Greeting", 0);

        // 获取系统运行时间
        uint tickCount = Win32Api.GetTickCount();
        Console.WriteLine($"System uptime: {tickCount} ms");

        // 获取窗口位置
        Win32Api.RECT rect;
        bool success = Win32Api.GetWindowRect(new IntPtr(0x123456), out rect);
        if (success)
        {
            Console.WriteLine($"Window Rect: {rect.Left}, {rect.Top}, {rect.Right}, {rect.Bottom}");
        }
    }
}

通过掌握 DllImport 和 P/Invoke,你可以在 C# 中直接调用 Windows API 或其他非托管函数,实现更底层的系统级操作。结合良好的封装和错误处理,可以显著提升程序的功能性和灵活性。

总结

到此这篇关于Java快速转C#的文章就介绍到这了,更多相关Java快速转C#内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文