迭代C#中的对象字段

Vla*_*tch 1 c# reflection object

Foo是一个包含大量字符串字段的类.我想创建一个方法Wizardify,在对象的许多字段上执行操作.我可以这样做:

Foo Wizardify(Foo input)
{
    Foo result;
    result.field1 = Bar(input.field1);
    result.field2 = Bar(input.field2);
    result.field3 = Bar(input.field3);
    ...
Run Code Online (Sandbox Code Playgroud)

这是一些易于生成的代码,但我不想在此上浪费50行.有没有办法浏览对象的选定字段?请注意,我想以不同的方式处理四个或五个字段,并且应该从迭代中排除它们.

Yah*_*hia 5

尝试

foreach ( FieldInfo FI in input.GetType().GetFields () )
{
    FI.GetValue (input)
    FI.SetValue (input, someValue)
}
Run Code Online (Sandbox Code Playgroud)

虽然我不推荐已知类型的反射方法 - 它很慢,并且根据您的具体情况可能会在运行时出现一些权限问题...


SLa*_*aks 0

循环typeof(YourType).GetProperties()并调用GetValueSetValue

请注意,反射相当慢。