Ism*_*ilS 6 c# reflection .net-3.5 c#-3.0
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";
Run Code Online (Sandbox Code Playgroud)
考虑上面的类以及稍后的初始化.现在,在某些时候,我想在发生错误时记录其状态.我想得到字符串日志有点像下面.
string toLog = Helper.GetLogFor(emp1Address);
Run Code Online (Sandbox Code Playgroud)
sting toLog应该如下所示.
AddressLine1 = "Microsoft Corporation";
AddressLine2 = "One Microsoft Way";
City = "Redmond";
State = "WA";
Zip = "98052-6399";
Run Code Online (Sandbox Code Playgroud)
然后我会记录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();
}
Run Code Online (Sandbox Code Playgroud)
Bry*_*tts 22
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();
}
Run Code Online (Sandbox Code Playgroud)
static void Log(object @object)
{
foreach (var property in @object.GetType().GetProperties())
Console.WriteLine(property.Name + ": " + property.GetValue(@object, null).ToString());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8421 次 |
| 最近记录: |