csharp 修剪所有对象的字符串。
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp 修剪所有对象的字符串。相关的知识,希望对你有一定的参考价值。
// Use like this
MyObject obj = new MyObject();
ExtensionMethods.TrimAllStrings(obj);
public static class ExtensionMethods
{
public static void TrimAllStrings<TSelf>(this TSelf obj)
{
if (obj == null)
return;
BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy;
foreach (PropertyInfo p in obj.GetType().GetProperties(flags))
{
Type currentNodeType = p.PropertyType;
if (currentNodeType == typeof(String))
{
string currentValue = (string)p.GetValue(obj, null);
if (currentValue != null)
{
p.SetValue(obj, currentValue.Trim(), null);
}
}
// see http://stackoverflow.com/questions/4444908/detecting-native-objects-with-reflection
else if (currentNodeType != typeof(object) && Type.GetTypeCode(currentNodeType) == TypeCode.Object)
{
if (p.GetIndexParameters().Length == 0)
{
p.GetValue(obj, null).TrimAllStrings();
}
else
{
p.GetValue(obj, new Object[] { 0 }).TrimAllStrings();
}
}
}
}
}
以上是关于csharp 修剪所有对象的字符串。的主要内容,如果未能解决你的问题,请参考以下文章