Поиск  
Always will be ready notify the world about expectations as easy as possible: job change page
2 дня назад

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

Как получить информацию об объекте в C#
Автор:
Сергей Дроздов
Просмотров:
61
Как получить информацию об объекте в 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

Файлы

Похожее
Dec 23, 2023
Author: Juldhais Hengkyawan
This article will teach us how to retrieve the client’s IP address and location information in ASP.NET Core web development. Retrieve the client IP from HttpContext In ASP.NET Core, you can easily get the client IP address from the HttpContext...
Nov 27, 2023
Author: Juldhais Hengkyawan
Use the Bogus library to generate and insert 1 million dummy product data into the SQL Server database. We need to create 1 million dummy product data into the SQL Server database, which can be used for development or performance...
Jul 25, 2023
Unleashing the Power of Meta-Programming: A Comprehensive Guide to C# Reflection Reflection, put simply, is a mechanism provided by the .NET framework that allows a running program to examine and manipulate itself. It’s like a coding mirror that gives your...
Jun 29, 2023
Author: Megha Prasad
Attributes and decorators, which allow you to attach metadata to classes, properties, and methods. Attributes Attributes in C# allow you to attach metadata to your classes, methods, and other code elements. This metadata can then be used at runtime to...
Написать сообщение
Тип
Почта
Имя
*Сообщение