Skip to content

Instantly share code, notes, and snippets.

@mgravell
Created April 15, 2020 10:46
Show Gist options
  • Save mgravell/57d5691741e1379f32c2d22540acf8da to your computer and use it in GitHub Desktop.
Save mgravell/57d5691741e1379f32c2d22540acf8da to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
class Foo
{
[SomeAttrib]
public EntityLocalizer A { get; set; }
[SomeAttrib]
private EntityLocalizer B { get; set; }
[SomeAttrib]
public EntityLocalizer C;
[SomeAttrib]
private EntityLocalizer D;
}
public class SomeAttribAttribute : Attribute { }
public class EntityLocalizer { }
static class P
{
static void Main()
{
Thing(typeof(Foo));
}
static void Thing(Type entityType)
{
var locFields = EntityLocalizationReflection.GetLocalizationFields(entityType);
if (locFields?.Count > 0)
{
var entityObject = Expression.Parameter(typeof(object), "objParam");
var entityInstance = Expression.Convert(entityObject, entityType);
foreach (var loc in locFields)
{
var target = loc.Item2.MemberType == MemberTypes.Property
? Expression.Property(entityInstance, (PropertyInfo)loc.Item2)
: Expression.Field(entityInstance, (FieldInfo)loc.Item2);
var getter = Expression.Lambda<Func<object, EntityLocalizer>>(target, entityObject);
getter.Compile();
Console.WriteLine("compiled for " + loc.Item1);
}
}
}
}
internal class EntityLocalizationReflection
{
internal static List<(string, MemberInfo)> GetLocalizationFields(Type entityType)
{
MemberInfo[] fields = entityType.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic);
MemberInfo[] props = entityType.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic);
return fields.Concat(props).Where(x => Attribute.IsDefined(x, typeof(SomeAttribAttribute)))
.OrderBy(x => x.Name).Select(x => (x.Name, x)).ToList();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment