string s1 = "строка \"с кучей\" ковычек";
string s2 = @"строка ""с кучей"" ковычек";
object[] arr = new object[]
{
"Hello World!",
new object[]
{
"Hello_1",
"Hello_2"
}
};
foreach (object item in arr)
{
if (item is string str)
{
Console.WriteLine(str);
}
else if (item is object[] subarr)
{
foreach (object subitem in subarr)
{
Console.WriteLine(subitem);
}
}
}
object[] arr = new object[]
{
"Hello World!",
new object[]
{
"Hello_1",
"Hello_2",
new object[]
{
"Hello_11",
"Hello_22"
}
}
};
foreach (object item in arr)
{
ItemAction(item, str => Console.WriteLine(str));
}
static void ItemAction(object item, Action<string> action)
{
if (item is string str)
{
action(str);
}
else if (item is object[] arr)
{
foreach (object subitem in arr)
{
ItemAction(subitem, action);
}
}
}
var figure = new Circle(); // тип известен заранее (при компиляции)
Console.WriteLine(figure.CalcArea());
var type = Console.ReadLine();
Figure figure = null;
switch (type.ToLower())
{
case "square": figure = new Square(10); break;
case "rectangle": figure = new Rect(10, 20); break;
case "circle": figure = new Circle(10); break;
}
if (figure != null)
{
Console.WriteLine(figure.CalcArea());
}
else
{
Console.WriteLine("Неверный тип фигуры");
}
var typeName = Console.ReadLine();
var type = Type.GetType(typeName);
if (type != null)
var figure = (Figure)Activator.CreateInstance(type);
Console.WriteLine(figure.CalcArea());
}
else
{
Console.WriteLine("Неверный тип");
}
class Anime
{
public string Name {get; set;}
public double Rating {get; set;}
public string Author {get; set;}
public string Serie {get; set;}
public string Url {get; set;}
}
class AnimeListViewModel
{
public ObservableCollection<Anime> AnimeList {get; set;} = new ObservableCollection<Anime>
{
new Anime { Name = "Наруто", Rating = 5, Author = "Масаси Кисимото"},
new Anime { Name = "Стальной алхимик", Rating = 5, Author = "Хирому Аракава"},
new Anime { Name = "X", Rating = 5, Author = "CLAMP"},
};
}
<Window ...
xmlns:app="clr-namespace:Anime">
<Window.DataContext>
<app:AnimeListViewModel/>
</Window.DataContext>
<Grid>
<ListBox ItemsSource="{Binding AnimeList}"
DisplayMemberPath="Name"/>
x:Name="AnimeListBox"/>
</Grid>
</Window>
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string MiddleName { get; set; }
}
public class EditPersonVm : BaseViewModel // который реализует INotifyPropertyChanged
{
private readonly Person _person;
public Person Person => _person;
private string _firstName;
public string FirstName
{
get => _firstName;
set { _firstName = value; RaisePropertyChanged(); }
}
private string _lastName;
public string LastName
{
get => _lastName;
set { _lastName= value; RaisePropertyChanged(); }
}
private string _middleName;
public string MiddleName
{
get => _middleName;
set { _middleName= value; RaisePropertyChanged(); }
}
public string InitFullName => $"{_person.LastName} {_person.FirstName[0]}. {_person.MiddleName[0]}.";
public RelayCommand OkButton { get; set; } = new RelayCommand(Save);
public EditPersonVm(Person person)
{
_person = person;
FirstName = person.FirstName;
LastName = person.LastName;
MiddleName = person.MiddleName;
}
private void Save()
{
//
}
}
<Window ...>
<StackPanel Orientation="Vertical">
<Label Content="Изначальное имя:"/>
<StackPanel>
<TextBlock Text="{Binding Person.LastName}"/>
<TextBlock> </TextBlock>
<TextBlock Text="{Binding Person.FirstName}"/>
<TextBlock> </TextBlock>
<TextBlock Text="{Binding Person.MiddleName}"/>
</StackPanel>
<Label Content="Фамилия:"/>
<TextBox Text="{Binding LastName, UpdateSourceTrigger=PropertyChanged}"/>
<Label Caption="Имя:"/>
<TextBox Text="{Binding FirstName, UpdateSourceTrigger=PropertyChanged}"/>
<Label Caption="Отчество:"/>
<TextBox Text="{Binding MiddleName, UpdateSourceTrigger=PropertyChanged}"/>
<Button Content="OK" Command="{Binding OkCommand}">
</StackPanel>
</Window>
int cnt1 = 0, cnt2 = 0, cnt3 = 0;
var t0 = DateTime.Now;
for (int i = 0; i <= 999999; i++)
{
var a1 = i / 100000 % 10;
var a2 = i / 10000 % 10;
var a3 = i / 1000 % 10;
var b1 = i / 100 % 10;
var b2 = i / 10 % 10;
var b3 = i / 1 % 10;
if (a1 + a2 + a3 == b1 + b2 + b3) cnt1++;
}
var t1 = DateTime.Now;
for (int a1 = 0; a1 <= 9; a1++)
for (int a2 = 0; a2 <= 9; a2++)
for (int a3 = 0; a3 <= 9; a3++)
for (int b1 = 0; b1 <= 9; b1++)
for (int b2 = 0; b2 <= 9; b2++)
for (int b3 = 0; b3 <= 9; b3++)
{
if (a1 + a2 + a3 == b1 + b2 + b3) cnt2++;
}
var t2 = DateTime.Now;
for (int i = 0; i <= 999999; i++)
{
string kstr = i.ToString("D6");
var a1 = int.Parse(kstr[0] + "");
var a2 = int.Parse(kstr[1] + "");
var a3 = int.Parse(kstr[2] + "");
var b1 = int.Parse(kstr[3] + "");
var b2 = int.Parse(kstr[4] + "");
var b3 = int.Parse(kstr[5] + "");
if (a1 + a2 + a3 == b1 + b2 + b3) cnt3++;
}
var t3 = DateTime.Now;
Console.WriteLine($"{cnt1} {(t1 - t0).TotalMilliseconds} мс"); // 55252 21,0197 мс
Console.WriteLine($"{cnt2} {(t2 - t1).TotalMilliseconds} мс"); // 55252 1,8051 мс
Console.WriteLine($"{cnt3} {(t3 - t2).TotalMilliseconds} мс"); // 55252 106,1106 мс
int Count_Good = 0, Count_Bad = 0;
// получаем словари в память, чтобы не открывать файлы словарей повторно
// а также переводим слова в строчные
var goods = File.ReadAllLines("slovar_good.txt").Select(word => word.ToLower());
var bads = File.ReadAllLines("slovar_bad.txt").Select(word => word.ToLower());
var file = File.OpenText(@"C:\Users\pavlovaa\Desktop\hik.txt");
string str;
while ((str = file.ReadLine()) != null)
{
str = str.ToLower();
Count_Good += CountWords(str, goods);
Count_Bad += CountWords(str, bads);
}
int CountWords(string str, IEnumerable<string> words)
{
if (string.IsNullOrWhiteSpace(str)) return 0;
var count = 0;
foreach (var word in words)
{
if (string.IsNullOrWhiteSpace(word)) continue;
int pos;
while ((pos = str.IndexOf(word)) != -1)
{
count++;
str = str.Substring(pos + word.Length);
}
}
return count;
}
i:InvokeCommandAction
из System.Windows.Interactivity
.System.Windows.Interactivity
с помощью добавления ссылки (она в списке расширений).xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
i:EventTrigger
и i:InvokeCommandAction
:<TextBox>
<i:Interaction.Triggers>
<i:EventTrigger EventName="KeyDown">
<i:InvokeCommandAction Command="{Binding KeyDownCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBox>
string s = "<div>Здесь нам нужно заменить некоторый текст, текст, текст</div>";
var word = "текст";
var replaceTo = "ТЕКСТ";
var words = new List<int>();
int lastPos = 0;
int pos = 0;
do
{
pos = s.IndexOf(word, lastPos);
if (pos >= 0)
{
words.Add(pos);
lastPos = pos + word.Length;
}
}
while (pos >= 0);
var result = s.Substring(0, words[0]) + replaceTo + s.Substring(words[0] + word.Length);
string s = "<div>Здесь нам нужно заменить некоторый текст, текст, текст</div>";
var word = "текст";
var replaceTo = "ТЕКСТ";
var words = new Regex(word).Matches(s).OfType<Match>().Select(match => match.Index).ToList();
var result = s.Substring(0, words[0]) + replaceTo + s.Substring(words[0] + word.Length);
if (e.KeyChar != (char)Keys.Back && !Regex.Match(Symbol, @"[а-яА-Я]|[a-zA-Z]").Success)
Т.е. data[index] - это у нас объект класса Person
GetProperty()
и SetProperty(<type> value)
.GetIndexator(int index)
и SetIndexator(int index, <type> value)
.Person[] data;
public string this[int index]
{
get
{
return data[index]?.Name;
}
set
{
if (data[index] == null) data[index] = new Person();
data[index].Name = value;
}
}
Person[] data;
public Person this[string name]
{
get
{
return data.FirstOrDefault(p => p.Name == name);
}
set
{
for (var index = 0; index < data.Length; index++)
{
if (person.Name == name)
{
data[index] = value;
break;
}
}
}
}
set
{
data[index].Name = value;
}
А что если там не один только Name будет, ещё поля ??..
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Back)
{
var selectionStart = textBox1.SelectionStart;
if (textBox1.SelectionLength > 0)
{
textBox1.Text = textBox1.Text.Substring(0, selectionStart) + textBox1.Text.Substring(selectionStart + textBox1.SelectionLength);
textBox1.SelectionStart = selectionStart;
}
else if (selectionStart > 0)
{
textBox1.Text = textBox1.Text.Substring(0, selectionStart - 1) + textBox1.Text.Substring(selectionStart);
textBox1.SelectionStart = selectionStart - 1;
}
e.Handled = true;
}
}