Optimize ToString() method override

This commit is contained in:
弘韬 张 2021-02-14 12:02:59 +08:00
parent f93dcaef73
commit aabb820f6f
2 changed files with 13 additions and 24 deletions

View file

@ -58,13 +58,12 @@ namespace Flow.Launcher.Core.Plugin
string rpc = string.Empty;
if (Parameters != null && Parameters.Length > 0)
{
string parameters = Parameters.Aggregate("[", (current, o) => current + (GetParameterByType(o) + ","));
parameters = parameters.Substring(0, parameters.Length - 1) + "]";
rpc = string.Format(@"{{\""method\"":\""{0}\"",\""parameters\"":{1}", Method, parameters);
string parameters = $"[{string.Join(',', Parameters.Select(GetParameterByType))}]";
rpc = $@"{{\""method\"":\""{Method}\"",\""parameters\"":{parameters}";
}
else
{
rpc = string.Format(@"{{\""method\"":\""{0}\"",\""parameters\"":[]", Method);
rpc = $@"{{\""method\"":\""{Method}\"",\""parameters\"":[]";
}
return rpc;
@ -72,26 +71,16 @@ namespace Flow.Launcher.Core.Plugin
}
private string GetParameterByType(object parameter)
=> parameter switch
{
if (parameter == null) {
return "null";
}
if (parameter is string)
{
return string.Format(@"\""{0}\""", ReplaceEscapes(parameter.ToString()));
}
if (parameter is int || parameter is float || parameter is double)
{
return string.Format(@"{0}", parameter);
}
if (parameter is bool)
{
return string.Format(@"{0}", parameter.ToString().ToLower());
}
return parameter.ToString();
}
null => "null",
string _ => $@"\""{ReplaceEscapes(parameter.ToString())}\""",
bool _ => $@"{parameter.ToString().ToLower()}",
_ => parameter.ToString()
};
private string ReplaceEscapes(string str)
private string ReplaceEscapes(string str)
{
return str.Replace(@"\", @"\\") //Escapes in ProcessStartInfo
.Replace(@"\", @"\\") //Escapes itself when passed to client

View file

@ -119,7 +119,7 @@ namespace Flow.Launcher.Core.Plugin
/// <param name="arguments"></param>
/// <param name="token">Cancellation Token</param>
/// <returns></returns>
protected async Task<string> ExecuteAsync(string fileName, string arguments, CancellationToken token = default)
protected Task<string> ExecuteAsync(string fileName, string arguments, CancellationToken token = default)
{
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = fileName;
@ -128,7 +128,7 @@ namespace Flow.Launcher.Core.Plugin
start.CreateNoWindow = true;
start.RedirectStandardOutput = true;
start.RedirectStandardError = true;
return await ExecuteAsync(start, token);
return ExecuteAsync(start, token);
}
protected string Execute(ProcessStartInfo startInfo)