我有多个大对象,每个对象都有大约60个字符串.我必须修剪所有这些字符串,我想这样做,而不必去this.mystring = this.mystring.Trim().相反,我正在寻找一种方法来自动使每个对象发现自己的字符串,然后执行操作.
我知道一点反思,但还不够,但我认为这是可能的?
另外,我不知道这是否重要,但一些字符串属性是只读的(只有一个getter),所以这些属性将被跳过.
帮帮我?
解决方法@H_404_10@
那么,获取所有的属性很容易,并且找出哪些是字符串和可写的. LINQ使它更容易.
- var props = instance.GetType()
- .GetProperties(BindingFlags.Instance | BindingFlags.Public)
- // Ignore non-string properties
- .Where(prop => prop.PropertyType == typeof(string))
- // Ignore indexers
- .Where(prop => prop.GetIndexParameters().Length == 0)
- // Must be both readable and writable
- .Where(prop => prop.CanWrite && prop.CanRead);
-
- foreach (PropertyInfo prop in props)
- {
- string value = (string) prop.GetValue(instance,null);
- if (value != null)
- {
- value = value.Trim();
- prop.SetValue(instance,value,null);
- }
- }
您可能只想设置属性,如果修剪实际上有所作为,以避免复杂属性的冗余计算 – 或者这可能不是您的问题.
>只需缓存每种类型的相关属性
>使用Delegate.CreateDelegate构建getter和setter的代理
>可能使用表情树,虽然我不知道他们是否会帮助这里
我不会采取任何这些步骤,除非性能实际上是一个问题.
- var props = instance.GetType()
- .GetProperties(BindingFlags.Instance | BindingFlags.Public)
- // Ignore non-string properties
- .Where(prop => prop.PropertyType == typeof(string))
- // Ignore indexers
- .Where(prop => prop.GetIndexParameters().Length == 0)
- // Must be both readable and writable
- .Where(prop => prop.CanWrite && prop.CanRead);
- foreach (PropertyInfo prop in props)
- {
- string value = (string) prop.GetValue(instance,null);
- if (value != null)
- {
- value = value.Trim();
- prop.SetValue(instance,value,null);
- }
- }
您可能只想设置属性,如果修剪实际上有所作为,以避免复杂属性的冗余计算 – 或者这可能不是您的问题.
>只需缓存每种类型的相关属性
>使用Delegate.CreateDelegate构建getter和setter的代理
>可能使用表情树,虽然我不知道他们是否会帮助这里
我不会采取任何这些步骤,除非性能实际上是一个问题.