本文介绍了对象的记录状态.获取其所有属性值作为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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";
考虑上一类,然后再进行其初始化.现在,我想在发生错误时记录其状态.我想获得如下所示的字符串日志.
Consider above class and later its initialization. Now at some point I want to log its state when error occurs. I would like to get the string log somewhat like below.
string toLog = Helper.GetLogFor(emp1Address);
将toLog设置为如下所示.
sting toLog should look something like below.
AddressLine1 = "Microsoft Corporation";
AddressLine2 = "One Microsoft Way";
City = "Redmond";
State = "WA";
Zip = "98052-6399";
然后我将记录 toLog
字符串.
如何在 Helper.GetLogFor()
方法中访问对象的所有属性名称和属性值?
How can I access all the property names and property values of an object within Helper.GetLogFor()
method?
我实施的解决方案:-
/// <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();
}
这篇关于对象的记录状态.获取其所有属性值作为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!