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();
}
}
}
检查操作系统:
System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform 方法来检测当前运行的操作系统(Windows、Linux 或 macOS)。用户输入:
Console.ReadLine() 获取用户输入,并输出个性化的问候语。文件操作:
System.IO.File.WriteAllText 和 System.IO.File.ReadAllText 进行文件的写入和读取操作,这些方法是跨平台的,可以在不同操作系统上正常工作。控制台交互:
Console.WriteLine 和 Console.ReadKey 实现简单的控制台交互,确保程序不会立即退出。这个示例展示了如何编写一个简单但功能完整的跨平台 C# 应用程序。
上一篇:c# double转int
下一篇:c# span
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站