Search  
Always will be ready notify the world about expectations as easy as possible: job change page
2 days ago

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

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

Files

Similar
Jan 15, 2024
Author: MESCIUS inc.
HyperText markup language, commonly referred to as HTML, has been the foundation of creating and navigating web pages from the very beginning. Its significance further increases provided how the world is moving towards digitization. Hence, working with this format just...
Feb 10, 2023
Author: Hr. N Nikitins
Design patterns are essential for creating maintainable and reusable code in .NET. Whether you’re a seasoned developer or just starting out, understanding and applying these patterns can greatly improve your coding efficiency and overall development process. In this post, we’ll...
Jan 1, 2023
Author: Matt Eland
New and old ways of creating your own exceptions in dotnet with C# 11 and .NET 7. Let’s talk about building custom exceptions in C# code and why you’d want to do that. We’ll cover the traditional way as well...
May 29, 2023
Maximizing performance in asynchronous programming Task and Task<TResult> The Task and Task<TResult> types were introduced in .NET 4.0 as part of the Task Parallel Library (TPL) in 2010, which provided a new model for writing multithreaded and asynchronous code. For...
Send message
Type
Email
Your name
*Message