Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# 跨平台

作者:★执着唯她   发布日期:2026-05-04   浏览:59

using System;

namespace CrossPlatformApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("这是一个跨平台的C#应用程序。");

            // 检查当前操作系统
            if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                Console.WriteLine("当前运行在 Windows 系统上");
            }
            else if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                Console.WriteLine("当前运行在 Linux 系统上");
            }
            else if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                Console.WriteLine("当前运行在 macOS 系统上");
            }
            else
            {
                Console.WriteLine("当前运行在一个未知的操作系统上");
            }

            // 示例:读取用户输入
            Console.Write("请输入您的名字: ");
            string name = Console.ReadLine();
            Console.WriteLine($"你好, {name}!");

            // 示例:文件操作(跨平台)
            string filePath = "example.txt";
            System.IO.File.WriteAllText(filePath, "这是一个跨平台的示例文件。");

            if (System.IO.File.Exists(filePath))
            {
                Console.WriteLine($"文件已创建: {filePath}");
                string fileContent = System.IO.File.ReadAllText(filePath);
                Console.WriteLine($"文件内容: {fileContent}");
            }

            Console.WriteLine("按任意键退出...");
            Console.ReadKey();
        }
    }
}

解释说明

  1. 检查操作系统

    • 使用 System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform 方法来检测当前运行的操作系统(Windows、Linux 或 macOS)。
  2. 用户输入

    • 通过 Console.ReadLine() 获取用户输入,并输出个性化的问候语。
  3. 文件操作

    • 使用 System.IO.File.WriteAllTextSystem.IO.File.ReadAllText 进行文件的写入和读取操作,这些方法是跨平台的,可以在不同操作系统上正常工作。
  4. 控制台交互

    • 使用 Console.WriteLineConsole.ReadKey 实现简单的控制台交互,确保程序不会立即退出。

这个示例展示了如何编写一个简单但功能完整的跨平台 C# 应用程序。

上一篇:c# double转int

下一篇:c# span

大家都在看

c# 二进制

c# 创建目录

c# socket服务端连接多个客户端

c# datatable group by

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

c# invoke方法

.net和c#

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站