在C#中格式化字符串的最佳方法

时间:2015-05-22 08:38:24

标签: vb.net visual-studio-2010

我有两种格式,如下所示。

格式1:

printstring = printstring & "---------------------------------------" & vbNewLine

格式2:

printstring = String.Format("{0}---------------------------------------{1}", printstring, vbNewLine)

建议您使用代码优化工具格式2

这有什么具体原因吗?像记忆消耗还是其他一些原因?

2 个答案:

答案 0 :(得分:1)

您的代码遭受SQL注入。

字符串格式对于大字符串比字符串连接更有效。它们也稍微容易阅读。两者都完全有效。

要修复你的sql注入,你需要对你的查询进行paramatarize:

using System;
using System.Data.SqlClient;

class Program
{
    static void Main()
    {
    //
    // The name we are trying to match.
    //
    string dogName = "Fido";
    //
    // Use preset string for connection and open it.
    //
    string connectionString =
        ConsoleApplication1.Properties.Settings.Default.ConnectionString;
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();
        //
        // Description of SQL command:
        // 1. It selects all cells from rows matching the name.
        // 2. It uses LIKE operator because Name is a Text field.
        // 3. @Name must be added as a new SqlParameter.
        //
        using (SqlCommand command = new SqlCommand(
        "SELECT * FROM Dogs1 WHERE Name LIKE @Name", connection))
        {
        //
        // Add new SqlParameter to the command.
        //
        command.Parameters.Add(new SqlParameter("Name", dogName));
        //
        // Read in the SELECT results.
        //
        SqlDataReader reader = command.ExecuteReader();
        while (reader.Read())
        {
            int weight = reader.GetInt32(0);
            string name = reader.GetString(1);
            string breed = reader.GetString(2);
            Console.WriteLine("Weight = {0}, Name = {1}, Breed = {2}",
            weight,
            name,
            breed);
        }
        }
    }
    }
}

输出     (这取决于您的数据库内容。)

体重= 130,姓名= Fido,品种= Bullmastiff

答案 1 :(得分:0)

我可能在这里错了,但看起来“grd.CurrentRow.Cells(1).Value”将解析为c#代码中的值。然后,您打算将其发送到数据库。换句话说,您的格式2将在它进入数据库之前用值替换“grd.CurrentRow.Cells(1).Value”。您的格式1不会是不正确的,也不会起作用。

在性能方面,始终建议参数化查询,因为它允许在优化器中构建SQL Server(如果这是您正在使用的数据库)来构建查询计划以优化常规运行查询。它会将此计划存储在缓存中,因此如果您继续进行相同类型的查询,SQL Server应该知道在进行一次以上的调用后调用它的最佳方法。使用实体框架或存储过程进行数据访问将帮助您而不是构建硬编码的sql语句。

有关详细信息,请参阅以下链接: