首页 > 解决方案 > 动态网络链接 C#

问题描述

我想创建一个谷歌翻译链接,这取决于我的输入。为了让事情更清楚,这里是我的“动态链接”:

private static string _GoogleLink = $"https://translate.google.com/?hl=de#{_SourceLanguage}/{_TargetLanguage}/{_SourceInput}"

我想我很清楚我想做什么,但是链接不能这样工作,它只是进入

https://translate.google.com/?hl=de#//

在我的浏览器中。我用这个方法执行链接:

public static void Translate(string input, string sourceLang, string targetLang)
{
    _SourceInput = input;
    _TargetLanguage = targetLang;
    _SourceLanguage = sourceLang;

    System.Diagnostics.Process.Start(_GoogleLink);
}

标签: c#

解决方案


您的静态字段在静态创建时被评估,它永远不会使用正确的值“更新” - 使用属性而不是字段,每次调用 getter 时都会评估该字段。

private static string _GoogleLink => $"https://translate.google.com/?hl=de#{_SourceLanguage}/{_TargetLanguage}/{_SourceInput}";

或老派语法

private static string _GoogleLink { get { return $"https://translate.google.com/?hl=de#{_SourceLanguage}/{_TargetLanguage}/{_SourceInput}"; } }

但是你应该考虑重新设计你的方法:

//instead of void - use string as a return
public static string Translate(string input, string sourceLang, string targetLang)
{
    //instead of saving your passed values, into static fields - transform the string right here and now and return it
    return $"https://translate.google.com/?hl=de#{sourceLang}/{targetLang}/{input}";
}

我相信这种语法更容易理解。


推荐阅读