你需要使用反射来实现,主要是通过`Type.GetProperties`方法,应该不会太难,但我不知道是否有内置的方法可以实现。
正如leppie指出的那样,排序并不简单,您需要检查参数的顺序,这至少能让你知道属性类型的所有顺序。如果你只有不同的属性类型,那就没问题了。
如果你不关心顺序,你可以使用:
var array = t.GetType()
.GetProperties()
.Select(p => p.GetValue(t, null))
.ToArray();
编辑:我刚想到一个解决方法,但它是特定于实现的。 C#编译器使用泛型类型生成匿名类型。 因此,new { A = 5, B = "foo" }
实际上将创建一个类似于以下内容的匿名类型:
class <>_Anon<TA, TB>
{
internal <>_Anon(TA a, TB b)
}
这样你就可以根据泛型属性的通用类型确定属性名称的顺序,然后按照顺序从具体类型中获取属性。但是这样做很丑陋...
using System;
using System.Linq;
using System.Reflection;
class Test
{
static object[] ConvertAnonymousType(object value)
{
Type type = value.GetType();
var genericType = type.GetGenericTypeDefinition();
var parameterTypes = genericType.GetConstructors()[0]
.GetParameters()
.Select(p => p.ParameterType)
.ToList();
var propertyNames = genericType.GetProperties()
.OrderBy(p => parameterTypes.IndexOf(p.PropertyType))
.Select(p => p.Name);
return propertyNames.Select(name => type.GetProperty(name)
.GetValue(value, null))
.ToArray();
}
static void Main()
{
var value = new { A = "a", Z = 10, C = "c" };
var array = ConvertAnonymousType(value);
foreach (var item in array)
{
Console.WriteLine(item);
}
}
}