获取使用泛型随机数据 [英] Get random data using Generics

查看:150
本文介绍了获取使用泛型随机数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们的一个单元测试是填充我们的随机数据业务对象中的属性。

One of our unit tests is to populate properties within our business objects with random data.

这些属性是不同的固有类型的,所以我们想用仿制药的权力回报你在传递类型的数据线沿线的东西:

These properties are of different intrinsic types and therefore we would like to use the power of generics to return data of the type you pass in. Something along the lines of:

public static T GetData<T>()

您会如何去处理这个?将低层次的接口工作? (IConvertible)

How would you go about approaching this? Would a low level interface work? (IConvertible)

推荐答案

这取决于你想随机的数据,因为办法的或算法的您要使用完全不同,这取决于类型

It depends on what data you want to randomize, because the way or the algorithm you want to use is totally different depending on the type.

例如:

// Random int
Random r = new Random();
return r.Next();

// Random Guid
return Guid.NewGuid();

...



因此,这显然使得使用泛型一个不错的semplification用户的结束,但它增加了没有价值编写的类的方式。你可以使用一个开关条款或字典(如乔恩斯基特建议):

So this obviously makes the use of generics a nice semplification on the user's end, but it adds no value to the way you write the class. You could use a switch clause or a dictionary (like Jon Skeet suggests):

switch(typeof(T))
{
    case System.Int32:
        Random r = new Random();
        return (T)r.Next();
    case System.Guid:
        return (T)Guid.NewGuid();
    ...

然后,你期望你会使用的类:

Then you would use the class as you expect:

RandomGenerator.GetData<Guid>();
...

这篇关于获取使用泛型随机数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆