0

По нажатии на кнопку ничего не происходит

введите сюда описание изображения

namespace WpfApp1
{
/// <summary>
/// Логика взаимодействия для MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void btn1_Click(object sender, RoutedEventArgs e)
    {
        text1.Text.Insert(3, "-");
    }
}
}

1 ответ 1

4

В C# строковые переменные (тип String) являются неизменяемыми (immutable). По этой причине значение, которое хранится в поле свойства Text вашего тексбокса, остаётся прежним. Согласно документации, метод String.Insert(Int32, String), возвращает изменённую строку, но не изменяет исходную. Поэтому, Ваш метод должен выглядеть следующим образом:

private void btn1_Click(object sender, RoutedEventArgs e)
{
    text1.Text = text1.Text.Insert(3, "-");
}

Этот код выполнит вставку и вернёт изменённое значение, которое затем присвоится свойству Text для текстбокса.

Цитата из статьи Strings, immutability and persistence:

One of the benefits of the immutable data types I’ve talked about here previously is that they are not just immutable, they are also “persistent“. By “persistent”, I mean an immutable data type such that common operations on that type (like adding a new item to a queue, or removing an item from a tree) can re-use most or all of the memory of an existing data structure. Since it is all immutable, you can re-use its parts without worrying about them changing on you.

Strings in this format are immutable, but they are not persistent, thanks to that pesky single-buffer-with-both-a-prefix-and-suffix layout. Concatenation two strings does not re-use the content of either of the original strings; it creates a new string and copies the two strings into the new string. Taking the substring of a string does not re-use the content of the original string. Again, it just makes a new string of the right size and makes a full copy of the data.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.