Generate a random parameter value for a method without knowing the type of parameter

What problem do I want to solve? Through reflection, I want to execute code (running instance methods, as well as static methods), where I do not know in advance how the method that will be executed is determined.

Say I have MethodInfoone that I want to call. I do not know what parameters he has, so I do the following.

first, I check that the parameters of the method are valid (if they are not valid, then the method is not called):

 private static IEnumerable<Type> GetValidMethodTypes()
    {
        var validTypes = new List<Type>();
        validTypes.AddRange(new[]
        {
            typeof (SByte),
            typeof(String[]),
            //etc...
        });

        return validTypes;
    }

Then I generate random values ​​depending on the type of parameter:

 public object RandomizeParamValue(string typeName)
    {
        switch (typeName)
        {
            case "SByte":
            {
                //return randomized value
            }
            case "String[]":
            {
                //return randomized value
            }
            //etc...
        }
     }

, String [] [ "a", "ab", "ccc" ] [ "aa", "b" ]. : [ 1 5], . :)

, , . , . , , . , . - / ?

: , , :

void SomeMethod(unknowntypeatcompiletime param);

unknowntypeatcompiletime .

+4
2

, .

, , Mock TDD, Moq AutoFixture, ( ). , , , , .

, - . , . , , . , .

0

, .

.

- :

public class Randomizer
{
    private Dictionary<Type, Delegate> _randoms
        = new Dictionary<Type, Delegate>();

    public void Add<T>(Func<T> generate)
    {
        _randoms.Add(typeof(T), generate);
    }

    public T RandomizeParamValue<T>()
    {
        return ((Func<T>)_randoms[typeof(T)])();
    }
}

:

var rz = new Randomizer();
var rnd = new Random();
rz.Add(() => rnd.Next());
rz.Add(() => new [] { "a", "b", "c" }.ElementAt(rnd.Next(0, 3)));

, :

var randIntegers = rz.RandomizeParamValue<int>();
var randStrings = rz.RandomizeParamValue<string>();

. , .

0
source

Source: https://habr.com/ru/post/1542160/


All Articles