我如何遍历在C#中的匿名对象的属性? [英] How do I iterate over the properties of an anonymous object in C#?
问题描述
我要带一个匿名对象作为参数传递给方法,然后遍历其属性为每个属性/值添加到动态 ExpandoObject
。
所以,我需要的是去从
新{为prop1 =第一个值,Prop2 = SomeObjectInstance,Prop3 = 1234}
要了解每个属性的名称和值,并能够将它们添加到 ExpandoObject
。
我如何做到这一点?
边注:这将在我的很多单元测试来完成(我用它来重构走在设置了大量垃圾),因此性能在一定程度上相关。我不知道有足够的了解反射肯定地说,但就我的理解是pretty表现重,所以如果可能的话,我宁愿避免它...
后续问题:
正如我所说,我是在这个匿名对象作为参数的方法。我应该在方法的签名使用的是什么数据类型?所有属性将可用,如果我使用对象
?
的foreach(在myVar.GetType()的GetProperties(BindingFlags.Instance VAR道具|。BindingFlags.Public))
{
Console.WriteLine(名称:{0},值:{1},prop.Name,prop.GetValue(myVar的,NULL));
}
I want to take an anonymous object as argument to a method, and then iterate over its properties to add each property/value to a a dynamic ExpandoObject
.
So what I need is to go from
new { Prop1 = "first value", Prop2 = SomeObjectInstance, Prop3 = 1234 }
to knowing names and values of each property, and being able to add them to the ExpandoObject
.
How do I accomplish this?
Side note: This will be done in many of my unit tests (I'm using it to refactor away a lot of junk in the setup), so performance is to some extent relevant. I don't know enough about reflection to say for sure, but from what I've understood it's pretty performance heavy, so if it's possible I'd rather avoid it...
Follow-up question:
As I said, I'm taking this anonymous object as an argument to a method. What datatype should I use in the method's signature? Will all properties be available if I use object
?
foreach(var prop in myVar.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
Console.WriteLine("Name: {0}, Value: {1}",prop.Name, prop.GetValue(myVar,null));
}
这篇关于我如何遍历在C#中的匿名对象的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!