Difference between String, FormattableString, IFormattable

后端 未结 2 1075
青春惊慌失措
青春惊慌失措 2021-02-01 02:06

FormattableString has been Introduced in C# 6.0. As we can use same string formatting using string object why is there need of using FormattableS

2条回答
  •  走了就别回头了
    2021-02-01 02:36

    As an aside, https://www.meziantou.net/interpolated-strings-advanced-usages.htm covers some examples of what FormattableString allows you to do (e.g. auto-parameterising SQL statements)

    e.g.

    void ExecuteNonQuery(DbConnection connection, FormattableString formattableString)
    {
        using (var command = connection.CreateCommand())
        {
            // Replace values by @p0, @p1, @p2, ....
            var args = Enumerable.Range(0, formattableString.ArgumentCount).Select(i => (object)("@p" + i)).ToArray();
    
            command.CommandType = System.Data.CommandType.Text;
            command.CommandText = string.Format(formattableString.Format, args);
    
            // Create parameters
            for (var i = 0; i < formattableString.ArgumentCount; i++)
            {
                var arg = formattableString.GetArgument(i);
                var p = command.CreateParameter();
                p.ParameterName = "@p" + i;
                p.Value = arg;
                command.Parameters.Add(p);
            }
    
            // Execute the command
            command.ExecuteNonQuery();
        }
    }
    
    using (var sqlConnection = new SqlConnection())
    {
        sqlConnection.Open();
        ExecuteNonQuery(sqlConnection, $@"UPDATE Customers SET Name = {"Meziantou"} WHERE Id = {1}");
    }
    
    

提交回复
热议问题