Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- namespace StringParameters
- {
- // класс-пример
- // public int A { get; set; } - свойство
- // public int A; - поле
- // в работе разницы никакой, в строчке 23 (var fields = ...)
- // GetFields() выберет второй вариант,
- // если написать GetProperties() - первый
- class Foo
- {
- public int A;
- public int B;
- public int C { get; set; }
- }
- class Program
- {
- static void Main(string[] args)
- {
- Foo foo = new Foo {A = 13, B = 37, C = 1488};
- var fields = foo.GetType().GetFields(); // все поля класса Foo
- Dictionary<string, int> dict = new Dictionary<string, int>();
- foreach (var field in fields)
- {
- var val = field.GetValue(foo);
- Console.WriteLine("{0} = {1}", field.Name, val);
- dict.Add(field.Name, (int) val);
- }
- Console.WriteLine("-- *** --");
- string message = "A:325469B:24348C:228420";
- // тупа строчку разбиваем
- // i++ <=> return i; i = i + 1;
- // ++i <=> i = i + 1; return i;
- int i = 0;
- while (i < message.Length)
- {
- if (char.IsLetter(message[i]))
- {
- string currentField = message[i].ToString();
- while (message[++i] != ':')
- currentField += message[i];
- string currentValue = message[++i].ToString();
- while (char.IsDigit(message[++i]))
- {
- currentValue += message[i];
- if (i + 1 == message.Length)
- {
- i++;
- break;
- }
- }
- dict[currentField] = int.Parse(currentValue);
- }
- }
- // тупа закончили строчку разбивать
- for ( i = 0; i < fields.Length; i++)
- {
- foreach (var key in dict.Keys)
- if (fields[i].Name == key)
- fields[i].SetValue(foo, dict[key]);
- }
- Console.WriteLine($"A = {foo.A}");
- Console.WriteLine($"B = {foo.B}");
- Console.WriteLine($"C = {foo.C} - свойство не определилось методом GetFields()");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement