I need to get names of all properties of anonymous type exactly in the order they are declared.
To get them, I can use Type.GetProperties
method. It seems to return properties in "correct" order, but according to MSDN I cannot depend on it, because that order might vary.
I also found TypeInfo.DeclaredProperties
property which gives me result I expect, but I cannot found any info whether the order is guaranteed or not (at least MSDN doesn't explicitly state it's not guaranteed).
Or is there any other way? It's probably irrelevant, but the anonymous type is actually part of Expression
. But I'm not aware of anything in Expression Trees API which can help.
I'm targeting .NET Standard 2.0 and it should work on full .NET framework, .NET Core and Mono/Xamarin.
Sample code:
static void Main(string[] args)
{
Foo(() => new { Lorem = 1, Ipsum = 2, Dolor = "sit amet" });
}
static void Foo<T>(Expression<Func<T>> expression)
{
var node = (NewExpression)expression.Body;
// seems to work, but GetProperties doesn't guarantee order according to MSDN
var names1 = node.Type.GetProperties().Select(p => p.Name).ToArray();
// names1 = "Lorem", "Ipsum", "Dolor"
// seems to work, but is it "bulletproof"?
var names2 = node.Type.GetTypeInfo().DeclaredProperties.Select(p => p.Name).ToArray();
// names2 = "Lorem", "Ipsum", "Dolor"
}
Aucun commentaire:
Enregistrer un commentaire