1

Имеется следующий класс:

public class MyClass 
    { 
        public string StrProp1 {get; set;} 
        public string StrProp2 {get; set;} 
        public int IntProp {get; set;} 
        public DateTime? DTNullableProp {get; set;}
        public int? IntNullableProp {get; set;}

    }

Как получить коллекцию, например Dictionary<string, string> с парами "имя свойства" -> "значение". Значения, соответственно приводятся к типу string.

1 ответ 1

5

Попробуйте так:

o.GetType().GetProperties().ToDictionary(p => p.Name, p => p.GetValue(o)?.ToString());

Для C# 5, в котором нет ?., подойдёт чуть менее синтаксически красивый код:

o.GetType().GetProperties().ToDictionary(
        p => p.Name,
        p => { var v = p.GetValue(o); return v == null ? null : v.ToString(); }
);

Проверка: http://ideone.com/heZl2W

Ваш ответ

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

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