Ale*_*lex 11 .net c# reflection trim
我有多个大对象,每个对象有大约60个字符串.我必须修剪所有这些字符串,我想这样做而不必去this.mystring = this.mystring.Trim().相反,我正在寻找一种方法来自动让每个对象发现自己的字符串,然后执行操作.
我对反思有点了解,但还不够,但我认为这是可能的吗?
另外,我不确定这是否重要,但是一些字符串属性是只读的(只有一个getter),因此必须跳过这些属性.
救命?
Jon*_*eet 15
好吧,它很容易获得所有属性,并找出哪些属性是字符串和可写的.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);
}
}
Run Code Online (Sandbox Code Playgroud)
您可能只想设置属性,如果修剪实际上有所不同,以避免复杂属性的冗余计算 - 或者它可能不是一个问题.
如有必要,有多种方法可以改善性能 - 例如:
Delegate.CreateDelegate搭建的getter和setter代表我不会采取任何这些步骤,除非性能实际上是一个问题.
| 归档时间: |
|
| 查看次数: |
2942 次 |
| 最近记录: |