如何在 C# 中迭代匿名对象的属性? [英] How do I iterate over the properties of an anonymous object in C#?
问题描述
我想将匿名对象作为方法的参数,然后迭代其属性以将每个属性/值添加到动态 ExpandoObject
.
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
.
所以我需要的是从
new { Prop1 = "first value", Prop2 = SomeObjectInstance, Prop3 = 1234 }
了解每个属性的名称和值,并能够将它们添加到 ExpandoObject
.
to knowing names and values of each property, and being able to add them to the ExpandoObject
.
我该如何实现?
旁注:这将在我的许多单元测试中完成(我使用它来重构设置中的大量垃圾),因此性能在某种程度上是相关的.我对反射知之甚少,无法肯定地说,但据我所知,它的性能很重,所以如果可能的话,我宁愿避免它...
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...
后续问题:正如我所说,我将这个匿名对象作为方法的参数.我应该在方法的签名中使用什么数据类型?如果我使用 object
,所有属性都可用吗?
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屋!