2011-09-01 38 views
1

Foo是一个有很多字符串字段的类。我想创建一个方法Wizardify,对对象的许多字段执行操作。我可以这样做:迭代C中的对象字段#

Foo Wizardify(Foo input) 
{ 
    Foo result; 
    result.field1 = Bar(input.field1); 
    result.field2 = Bar(input.field2); 
    result.field3 = Bar(input.field3); 
    ... 

这是一些容易生成的代码,但我宁愿不浪费五十行。有没有办法查看对象的选定字段?请注意,我希望以不同的方式处理四个或五个字段,并且应该从迭代中排除它们。

+1

Bar是一种重载方法吗? – Ani

+0

@Ani:它的所有字段都是字符串。 –

回答

0

这是关于“优雅”,因为它得到。您可能可以使用for-loop,但正如您所说的,“我想以不同的方式处理四个或五个字段”。记住KISS原则。

0

通过typeof(YourType).GetProperties()循环并呼叫GetValueSetValue

请注意,反射速度很慢。

5

尝试

foreach (FieldInfo FI in input.GetType().GetFields()) 
{ 
    FI.GetValue (input) 
    FI.SetValue (input, someValue) 
} 

虽然我不会推荐的反射方式对已知类型的 - 它是缓慢的,并根据您的具体情况可能会造成在运行时的一些权限问题...

+1

,你可以用一些属性装饰你的领域,然后使用FI.Attributes;更多这里:http://stackoverflow.com/questions/156304/c-attributes-on-fields – bkdc

+1

我也不会建议使用反射这一点。这会很慢。您将要编写的代码量不会很大,从维护的角度来看它会更清晰。另外,你将在以后避免意想不到的后果。 –

+0

'+ 1'感谢分享!今天保存我的屁股:) – Anne

0

你可以使用动态语言运行时生成类型为Func的lambda。您只需要生成一次lambda(可以将其缓存),并且不会有反射性能下降。

0

这是我 - 它给了我在我的课的所有属性的列表(名称),到后来我可以反射或“表达式树”工作:

private static string xPrev = ""; 
     private static List<string> result; 

     private static List<string> GetContentPropertiesInternal(Type t) 
     { 
      System.Reflection.PropertyInfo[] pi = t.GetProperties(); 

      foreach (System.Reflection.PropertyInfo p in pi) 
      { 
       string propertyName = string.Join(".", new string[] { xPrev, p.Name }); 

       if (!propertyName.Contains("Parent")) 
       { 
        Type propertyType = p.PropertyType; 

        if (!propertyType.ToString().StartsWith("MyCms")) 
        { 
         result.Add(string.Join(".", new string[] { xPrev, p.Name }).TrimStart(new char[] { '.' })); 
        } 
        else 
        { 
         xPrev = string.Join(".", new string[] { xPrev, p.Name }); 
         GetContentPropertiesInternal(propertyType); 
        } 
       } 
      } 

      xPrev = ""; 

      return result; 
     } 

     public static List<string> GetContentProperties(object o) 
     { 
      result = new List<string>(); 
      xPrev = ""; 

      result = GetContentPropertiesInternal(o.GetType()); 

      return result; 
     } 

用法:List<string> myProperties = GetContentProperties(myObject);