通过对象自身的弦乐和放大器迭代;每次修剪 [英] Iterate through Object's own Strings & Trim each

查看:173
本文介绍了通过对象自身的弦乐和放大器迭代;每次修剪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个大对象,每个大约有60串。我不得不削减所有的字符串,我想,而不必去this.mystring = this.mystring.Trim这样做()。相反,我正在寻找一种方式来自动地让每个对象发现自己的字符串,然后再执行操作。

I have multiple large objects which each have about 60 strings. I have to trim all those strings, and I'd like to do so without having to go this.mystring = this.mystring.Trim(). Instead, I'm looking for a way to automatically have each object discover its own strings and then perform the operation.

我知道反思一点点,但还不够,但我认为这是可能的吗?

I know a little bit about reflection, but not enough, but I think this is possible?

此外,我不知道这事,但一些字符串属性是只读的(只能有一个getter),所以这些属性就必须被跳过。

Also, I'm not sure if this matters, but some string properties are read-only (only have a getter), so those properties would have to be skipped.

帮助?

推荐答案

嗯,这是很容易得到所有属性,并找出哪些是字符串,可写的。 LINQ使得它更容易

Well, it's easy enough to get all the properties, and find out which ones are strings and writable. LINQ makes it even easier.

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);
    }
}

您可能想,如果实际修剪只设置属性有差别,以避免复杂的性能冗余计算 - 也可能不是你一个问题。

You may want to only set the property if trimming actually makes a difference, to avoid redundant computations for complex properties - or it may not be an issue for you.

有改善必要时的表现不同的方式 - 比如

There are various ways of improving the performance if necessary - things like:


  • 只需缓存的相关属性,每种类型

  • 使用代表.CreateDelegate 来建立getter和setter

  • 可能使用表达式树的代表,虽然我不知道他们是否会有所帮助

  • Simply caching the relevant properties for each type
  • Using Delegate.CreateDelegate to build delegates for the getters and setters
  • Possibly using expression trees, although I'm not sure whether they'd help here

除非表现其实是一个问题,但我不会采取任何的那些步骤。

I wouldn't take any of those steps unless performance is actually a problem though.

这篇关于通过对象自身的弦乐和放大器迭代;每次修剪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆