Поиск  
Always will be ready notify the world about expectations as easy as possible: job change page
вчера

Как получить информацию об объекте в C#

Как получить информацию об объекте в C#
Автор:
Сергей Дроздов
Просмотров:
58
Как получить информацию об объекте в C# favorites 0

Во время разработки иногда нужно знать состояние объекта и какие данные в нём находятся. Debug не всегда подходит, иногда удобнее смотреть состояние объекта на веб-странице или может возникнуть необходимость сохранить информацию, например в файл.

Есть множество решений как реализовать эту задачу, и одно из простых и эффективных это написать Extension:

public static class Extensions
{
    public static string ObjectProperties(this object obj)
    {
        var properties = obj.GetType().GetProperties();
        var dump = new StringBuilder();
        foreach (var prop in properties)
        {
            dump.AppendLine($"{prop.Name}: {prop.GetValue(obj, null)}");
        }

        return dump.ToString();
    }
}

Вариант получения списка свойств:

public static class Extensions
{
    public static IList<string> ObjectPropertiesList(this object obj)
    {
        var properties = obj.GetType().GetProperties();

        return properties.Select(prop => $"{prop.Name}: {prop.GetValue(obj, null)}").ToList();
    }
}

Это рабочий вариант, но не показывает свойства вложенных объектов. В этой задаче нет необходимости показывать данные на множестве уровней вложенности, достаточно узнать про первый уровень.

public static IEnumerable<string> ObjectPropertiesFull(this object obj)
{
    var dump = new List<string>();
    var properties = obj.GetType().GetProperties();
    foreach (var prop in properties)
    {
        if (prop.GetValue(obj, null) is ICollection collectionItems)
        {
            dump.Add(prop.Name);
            foreach (var item in collectionItems)
            {
                dump.Add($" - {item}");
                var objectType = item.GetType();
                foreach (var nestedObjectProp in objectType.GetProperties())
                {
                    dump.Add($" --- {nestedObjectProp.Name}: {nestedObjectProp.GetValue(item)}");
                }
            }
        }
        else if (prop.GetValue(obj, null) is Object nestedObject)
        {
            dump.Add($"{prop.Name}: {prop.GetValue(obj, null)}");
            var nestedType = nestedObject.GetType();
            foreach (var nestedTypeProp in nestedType.GetProperties())
            {
                dump.Add($" --- {nestedTypeProp.Name}: {nestedTypeProp.GetValue(nestedObject)}");
            }
        }
    }

    return dump;
}

Этого в большинстве случаев достаточно. Если возникнет необходимость узнать больше информации об объекте - можно использовать рекурсию и более глубокий анализ свойств.

Codebase: https://codebase.blackball.lv/project/code-buns/source?file=Extensions/ObjectExtensions.cs#code-buns

Object properties

Файлы

Похожее
30 ноября 2020 г.
Если вы Web-разработчик и ведете разработку для браузера, то вы точно знакомы с JS, который может исполняться внутри браузера. Существует мнение, что JS не сильно подходит для сложных вычислений и алгоритмов. И хотя в последние годы JS cделал большой рывок...
Feb 2, 2024
With the release of C# 10 in November 2021 developers were introduced to a new concept called records, in this post I’ll outline some of the key differences between records and classes. For this comparison I’ll only consider the default/common...
May 13, 2023
Author: Juan Alberto España Garcia
Introduction to Async and Await in C# Asynchronous programming has come a long way in C#. Prior to the introduction of async and await, developers had to rely on callbacks, events and other techniques like the BeginXXX/EndXXX pattern or BackgroundWorker....
Jun 5, 2023
Author: Juan Alberto España Garcia
In this section, we’ll explore the world of unit testing in C# and .NET, learn what unit testing is, why it’s important, and the landscape of testing frameworks and tools available to developers. What is Unit Testing? Unit testing is...
Написать сообщение
Тип
Почта
Имя
*Сообщение
RSS