Diese Methode dient dazu, zufällige Ergebnisse für einen Datentyp zu erstellen.
Gaga gaga = new Gaga();
gaga.get<DATENTYP>(LÄNGE)
Console.WriteLine(gaga.get<int>(1));
Console.WriteLine(gaga.get<decimal>(2));
Console.WriteLine(gaga.get<float>(2));
Console.WriteLine(gaga.get<double>(8));
Console.WriteLine(gaga.get<int>(3));
Console.WriteLine(gaga.get<bool>());
Console.WriteLine(gaga.get<char>(7));
Console.WriteLine(gaga.get<string>(8));
Bei numerischen Werten mit Nachkommastelle bezieht sich die Länge auf die Vorkommastelle
using System;
using System.Linq;
namespace Project
{
class Gaga
{
readonly Random rnd = new Random();
const string CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
public dynamic get<T>(int length = 0)
{
if (length < 0)
throw new ArgumentOutOfRangeException("length");
else if(length == 0)
length = rnd.Next(0,20);
var type = typeof(T);
if (isNumeric(type))
{
length -= 1;
int min = (int)Math.Pow(10, length);
int max = (int)Math.Pow(10, length + 1) - 1;
if (isFloating(type) && (length < 20))
return (min + (rnd.NextDouble() * (max - min)));
else if(length < 10)
return rnd.Next(min, max);
}
else if (type == typeof(bool))
{
return rnd.NextDouble() >= 0.5;
}
else if (type == typeof(string) || type == typeof(char))
{
return new string(Enumerable.Repeat(CHARS, length).Select(s => s[rnd.Next(s.Length)]).ToArray());
}
return default(T);
}
private bool isNumeric(Type type)
{
return type == typeof(int) || type == typeof(double) || type == typeof(decimal) || type == typeof(float);
}
private bool isFloating(Type type)
{
return type == typeof(float) || type == typeof(double) || type == typeof(decimal);
}
}
}
1 Kommentare zum Snippet