清除C#中对象的所有字符串成员

xai*_*ain 2 c# reflection member clear

我有一个包含大约500个String成员的类,我想通过将它们设置为String.Empty来"重置"它们.任何人都可以告诉我如何使用反射这样做,所以我可以迭代每个String成员?

谢谢

Bal*_*a R 6

typeof(MyClass).GetProperties()
               .Where(p => p.PropertyType == typeof(string))
               .ToList()
               .ForEach(p => p.SetValue(myObj,string.Empty, null));
Run Code Online (Sandbox Code Playgroud)

编辑:

如果您正在处理字段而不是属性,则它非常相似

typeof(MyClass).GetFields()
               .Where(f => f.FieldType == typeof(string))
               .ToList()
               .ForEach(f => f.SetValue(myObj,string.Empty));
Run Code Online (Sandbox Code Playgroud)