Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Linq.Expressions;
- using System.Reflection;
- namespace Reflection.Randomness
- {
- public class Generator<T> where T : new()
- {
- private Dictionary<PropertyInfo, IContinousDistribution> properties;
- private string temporaryPropertyName;
- public Generator()
- {
- properties = typeof(T)
- .GetProperties()
- .Where(x => x.GetCustomAttributes(typeof(FromDistribution), false).Length != 0)
- .ToDictionary(x => x,
- x => ((FromDistribution)x
- .GetCustomAttribute(typeof(FromDistribution), false))
- .Distribution);
- }
- public T Generate(Random rnd)
- {
- var bindings = properties
- .Select(property => Expression.Bind(property.Key,
- Expression.Constant(property.Value.Generate(rnd))))
- .Cast<MemberBinding>()
- .ToList();
- var body = Expression.MemberInit(
- Expression.New(typeof(T).GetConstructor(new Type[0])),
- bindings
- );
- return Expression.Lambda<Func<T>>(body).Compile()();
- }
- public Generator<T> For(Expression<Func<T, double>> func)
- {
- var temporaryProperty = func.Body as MemberExpression;
- temporaryPropertyName = temporaryProperty.Member.Name;
- return this;
- }
- public Generator<T> Set(IContinousDistribution distr)
- {
- var property = typeof(T)
- .GetProperties()
- .First(x => x.Name == temporaryPropertyName);
- properties[property] = distr;
- return this;
- }
- }
- public class FromDistribution:Attribute
- {
- public IContinousDistribution Distribution { get; set; }
- public FromDistribution(Type type, params object[] parameters)
- {
- Distribution = (IContinousDistribution) Activator.CreateInstance(type, parameters);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement