c# - 动态网络链接 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);
}
解决方案
您的静态字段在静态创建时被评估,它永远不会使用正确的值“更新” - 使用属性而不是字段,每次调用 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}";
}
我相信这种语法更容易理解。
推荐阅读
- ios - 使用 twilio 向我的个人号码进行语音通话
- laravel - 我不想使用 laravel 在数组中显示空值
- python - psycopg2如何检查是否存在具有相同属性值的记录
- javascript - 如何解决素数索引元素的总和?
- java - 检测到 nodejs 版本后,Sonarqube CSS 分析失败
- python - 如何在 Sphinx 中将部分目录中的 rst 文件生成为 HTML 文件?
- typescript - 打字稿双同步/异步返回类型
- powershell - 字母数字排序在数组中不起作用
- mysql - Django 忽略 settings.py 中的数据库连接
- django - 如何使用 SQS 启动 Celery 容器