简体   繁体   English

高级C#重构

[英]Advanced C# Refactoring

As part of an internationalization effort it is required to refactor usages of string.Format(...) to use the string.Format(CultureInfo.InvariantCulture, ...) option when formatting SQL queries. 作为国际化工作的一部分,在格式化SQL查询时string.Format(CultureInfo.InvariantCulture, ...)需要重构string.Format(...)用法以使用string.Format(CultureInfo.InvariantCulture, ...)选项。 This is to ensure the code will continue to generate valid SQL when running under a variety of language-culture environments. 这是为了确保代码在各种语言文化环境下运行时将继续生成有效的SQL。 In other cases, for example when formatting strings for the UI, string.Format(...) usages should remain unchanged. 在其他情况下,例如,当格式化UI的字符串时, string.Format(...)用法应保持不变。

For example, the following code would need to be updated to use string.Format(CultureInfo.InvariantCulture, ...) : 例如,以下代码将需要更新以使用string.Format(CultureInfo.InvariantCulture, ...)

string sql;

if(somethign) 
{
    sql = string.Format("SELECT {0} FROM {1}", column, table);
}
else 
{
    sql = string.Format("SELECT {0} FROM {1}", column2, table2);
}

db.Query(sql);

Unfortunately this pattern of database access is used several thousand times in the code base and there is no straightforward find and replace command I can think of to use here. 不幸的是,这种数据库访问模式已在代码库中使用了数千次,并且没有可以想到的简单查找和替换命令。 Any find and replace approach needs to be advanced enough to isolate only the cases where the resulting string is used as a parameter to db.Query(). 任何查找和替换方法都需要足够先进,以仅隔离将结果字符串用作db.Query()参数的情况。

Some ideas I am currently considering include Resharper's Search with Pattern (I have never used it), writing a Roslyn based tool to intelligently refactor the code (seems over complicated) or some combination of Unix command line tools. 我目前正在考虑的一些想法包括Resharper的Search with Pattern(我从未使用过),编写基于Roslyn的工具来智能地重构代码(似乎有些复杂)或Unix命令行工具的某种组合。

I'm also open to other more significant refactoring approaches provided they can be largely automated. 我也愿意接受其他更重要的重构方法,只要它们可以在很大程度上实现自动化即可。

What is the recommended way to proceed with internationalizing this code? 进行此代码国际化的推荐方法是什么?

You can use string interpolation of C#. 您可以使用C#的字符串插值。 So the query will look like this: 因此查询将如下所示:

sql = $"SELECT {column} FROM {table}";

I think the default of string interpolation is current culture. 我认为字符串插值的默认值为当前文化。

On the other hand, I still don't recommend constructing your query in your code as it can be vulnerable to SQL injection. 另一方面,我仍然不建议在代码中构造查询,因为它很容易受到SQL注入的攻击。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM