gpt4 book ai didi

c# - 记录对象的状态。获取其所有属性值作为字符串

转载 作者:行者123 更新时间:2023-12-04 13:02:55 26 4
gpt4 key购买 nike

public class Address
{
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
}
......
var emp1Address = new Address();
emp1Address.AddressLine1 = "Microsoft Corporation";
emp1Address.AddressLine2 = "One Microsoft Way";
emp1Address.City = "Redmond";
emp1Address.State = "WA";
emp1Address.Zip = "98052-6399";

考虑上面的类,然后是它的初始化。现在在某些时候我想在发生错误时记录它的状态。我想获得类似于下面的字符串日志。
string toLog = Helper.GetLogFor(emp1Address);

sting toLog 应该如下所示。
AddressLine1 = "Microsoft Corporation";
AddressLine2 = "One Microsoft Way";
City = "Redmond";
State = "WA";
Zip = "98052-6399";

然后我会登录 toLog字符串。

如何访问 Helper.GetLogFor() 中对象的所有属性名称和属性值方法?

我实现的解决方案:-
/// <summary>
/// Creates a string of all property value pair in the provided object instance
/// </summary>
/// <param name="objectToGetStateOf"></param>
/// <exception cref="ArgumentException"></exception>
/// <returns></returns>
public static string GetLogFor(object objectToGetStateOf)
{
if (objectToGetStateOf == null)
{
const string PARAMETER_NAME = "objectToGetStateOf";
throw new ArgumentException(string.Format("Parameter {0} cannot be null", PARAMETER_NAME), PARAMETER_NAME);
}
var builder = new StringBuilder();

foreach (var property in objectToGetStateOf.GetType().GetProperties())
{
object value = property.GetValue(objectToGetStateOf, null);

builder.Append(property.Name)
.Append(" = ")
.Append((value ?? "null"))
.AppendLine();
}
return builder.ToString();
}

最佳答案

public static string GetLogFor(object target)
{
var properties =
from property in target.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)
select new
{
Name = property.Name,
Value = property.GetValue(target, null)
};

var builder = new StringBuilder();

foreach(var property in properties)
{
builder
.Append(property.Name)
.Append(" = ")
.Append(property.Value)
.AppendLine();
}

return builder.ToString();
}

关于c# - 记录对象的状态。获取其所有属性值作为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3446093/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com