如何在C#中实现英文文本到西班牙文的翻译?
在C#中英文字符串转西班牙文的正确方法
你之前用CultureInfo的方式无效,因为CultureInfo的作用是处理区域格式化(比如数字、日期、货币的显示规则),完全不具备文本翻译能力。下面是两种可行的实现方案:
方案一:使用翻译API(适合动态文本翻译)
可以借助Azure AI Translator服务实现动态文本翻译,步骤如下:
- 安装NuGet包:
Azure.AI.Translation.Text - 编写调用代码:
using Azure; using Azure.AI.Translation.Text; string apiKey = "你的Azure翻译API密钥"; string region = "你的服务区域(比如eastus)"; var client = new TextTranslationClient(new AzureKeyCredential(apiKey), region); string originalText = "my name is xyz"; Response<TranslatedText> response = await client.TranslateAsync("es", originalText); TranslatedText translation = response.Value.First(); string spanishText = translation.Translations.First().Text; Console.WriteLine(spanishText); // 输出: "me llamo xyz"
方案二:使用资源文件(适合固定静态文本)
如果是固定文本需要多语言支持,推荐使用.NET的资源文件系统:
- 在项目中添加资源文件:
- 创建
Resources.resx(默认英文),添加键值对:Bio→my name is xyz - 创建
Resources.es-ES.resx(西班牙文),添加键值对:Bio→me llamo xyz
- 创建
- 通过
ResourceManager获取对应语言的文本:
using System.Resources; using System.Globalization; // 设置目标文化 CultureInfo targetCulture = new CultureInfo("es-ES"); ResourceManager rm = new ResourceManager("你的项目命名空间.Resources", typeof(Program).Assembly); string spanishText = rm.GetString("Bio", targetCulture); Console.WriteLine(spanishText); // 输出: "me llamo xyz"
内容的提问来源于stack exchange,提问作者magnum S
相关产品推荐
相关产品推荐

