无需反射即可遍历C#中对象的所有字段

Iterate through all fields of an object in C# without Reflection
2021-02-23
  •  译文(汉语)
  •  原文(英语)

我有一个看起来像这样的代码

if( evento.ObjetosUnity != null ) lista_elementos.AddRange( evento.ObjetosUnity.Cast<Elemento3DJS>() );
if( evento.Imagenes3D != null ) lista_elementos.AddRange( evento.Imagenes3D.Cast<Elemento3DJS>() );
if( evento.Botones != null ) lista_elementos.AddRange( evento.Botones.Cast<Elemento3DJS>() );
...and so on...

我必须遍历对象的所有字段.有没有更简单的方法可以做到这一点?

编辑:我正在将一个应用程序编译为iOS,并且不能使用Reflection.

速聊1:
我想这个连结就是您要寻找的
速聊3:
您正在使用什么来编译应用程序?因为据我所知,Xamarin.iOS允许您使用Reflection,而不能用于动态代码生成(即Reflection.Emit).docs.xamarin.com/guides/ios/advanced_topics/limitations/…
解决过程1

简短的答案是"否".

没有反思,您将不得不阐明.是否要使用所有字段?为此编写代码.

I have a code that looks like this

if( evento.ObjetosUnity != null ) lista_elementos.AddRange( evento.ObjetosUnity.Cast<Elemento3DJS>() );
if( evento.Imagenes3D != null ) lista_elementos.AddRange( evento.Imagenes3D.Cast<Elemento3DJS>() );
if( evento.Botones != null ) lista_elementos.AddRange( evento.Botones.Cast<Elemento3DJS>() );
...and so on...

where I have to go through all the fields of an object. Is there an easier way of doing this?

Edit: I am compiling an App to iOS and CANT use Reflection.

Talk1:
I think this link is what you're looking for
Talk3:
What are you using to compile your app? Because as far as I know, Xamarin.iOS allows you to use Reflection, just not for dynamic code generation (i.e. Reflection.Emit). docs.xamarin.com/guides/ios/advanced_topics/limitations/…
Solutions1

The short answer is No.

Without reflection, you will have to spell it out. Want to use all fields? Write the code for it.

转载于:https://stackoverflow.com/questions/23692709/iterate-through-all-fields-of-an-object-in-c-sharp-without-reflection

本人是.net程序员,因为英语不行,使用工具翻译,希望对有需要的人有所帮助
如果本文质量不好,还请谅解,毕竟这些操作还是比较费时的,英语较好的可以看原文

留言回复
我们只提供高质量资源,素材,源码,坚持 下了就能用 原则,让客户花了钱觉得值
上班时间 : 周一至周五9:00-17:30 期待您的加入