Advertisement
VssA

active

Nov 2nd, 2023
1,047
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.21 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Linq.Expressions;
  5. using System.Reflection;
  6.  
  7. namespace Reflection.Randomness
  8. {
  9.     public class Generator<T> where T : new()
  10.     {
  11.         private Dictionary<PropertyInfo, IContinousDistribution> properties;
  12.         private string temporaryPropertyName;
  13.  
  14.         public Generator()
  15.         {
  16.             properties = typeof(T)
  17.                 .GetProperties()
  18.                 .Where(x => x.GetCustomAttributes(typeof(FromDistribution), false).Length != 0)
  19.                 .ToDictionary(x => x,
  20.                               x => ((FromDistribution)x
  21.                                   .GetCustomAttribute(typeof(FromDistribution), false))
  22.                                   .Distribution);
  23.         }
  24.  
  25.         public T Generate(Random rnd)
  26.         {
  27.             var bindings = properties
  28.                 .Select(property => Expression.Bind(property.Key,
  29.                                                     Expression.Constant(property.Value.Generate(rnd))))
  30.                 .Cast<MemberBinding>()
  31.                 .ToList();
  32.  
  33.             var body = Expression.MemberInit(
  34.                 Expression.New(typeof(T).GetConstructor(new Type[0])),
  35.                 bindings
  36.                 );
  37.             return Expression.Lambda<Func<T>>(body).Compile()();
  38.         }
  39.  
  40.         public Generator<T> For(Expression<Func<T, double>> func)
  41.         {
  42.             var temporaryProperty = func.Body as MemberExpression;
  43.             temporaryPropertyName = temporaryProperty.Member.Name;
  44.  
  45.             return this;
  46.         }
  47.  
  48.         public Generator<T> Set(IContinousDistribution distr)
  49.         {
  50.             var property = typeof(T)
  51.                 .GetProperties()
  52.                 .First(x => x.Name == temporaryPropertyName);
  53.             properties[property] = distr;
  54.  
  55.             return this;
  56.         }
  57.     }
  58.  
  59.     public class FromDistribution:Attribute
  60.     {
  61.         public IContinousDistribution Distribution { get; set; }
  62.  
  63.         public FromDistribution(Type type, params object[] parameters)
  64.         {
  65.             Distribution = (IContinousDistribution) Activator.CreateInstance(type, parameters);
  66.         }
  67.  
  68.     }
  69. }
  70.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement