34 lines
1.3 KiB
C#
34 lines
1.3 KiB
C#
using System.Text;
|
|
|
|
namespace adas_core.Domain.Utils;
|
|
|
|
/// <summary>
|
|
/// Provides static utility methods for common object-related operations.
|
|
/// </summary>
|
|
public static class ObjectUtils
|
|
{
|
|
/// <summary>
|
|
/// Converts an object to a string representation showing its type name and non-null property values in the format "TypeName[Property1: Value1,Property2: Value2]".
|
|
/// Returns "[OBJ NULL]" when the object is null, and skips properties whose values are null.
|
|
/// </summary>
|
|
/// <param name="obj">The object to convert to a string. Can be null.</param>
|
|
/// <returns>A string containing the type name followed by the object's non-null property values and their names.</returns>
|
|
public static string ToStr(this object? obj)
|
|
{
|
|
if (obj == null) return "[OBJ NULL]";
|
|
var type = obj.GetType();
|
|
//if (type == null) return "[OBJ TYPE NULL]";
|
|
StringBuilder sb = new();
|
|
sb.Append(type.Name + "[");
|
|
|
|
foreach (var property in obj.GetType().GetProperties())
|
|
{
|
|
var value = obj.GetType().GetProperty(property.Name)?.GetValue(obj);
|
|
if (value == null) continue;
|
|
sb.Append($"{property.Name}: {value},");
|
|
}
|
|
|
|
sb.Append(']');
|
|
return sb.ToString();
|
|
}
|
|
} |