2022/2/10
起始点:在ts中的常用工具方法:获得一个数组,随机返回数组内的一个值
step1:
public static T RandomArray
{
Random random = new Random();
int index = random.Next(0, arr.Length);
return arr[index];
}
step2:
发现需要随机的是一个枚举类型,将枚举类型转为数组,本来尝试自写,发现有方法可直接调用
Enum.GetValues(typeof(Animal));
但是其返回类型为Array,经过查找,此为数组类型的基类,尝试将其转为枚举数组,尝试失败,没有找到方法(基类不可转派生类?)
step3:
尝试转为数组失败后,引入List
List animal_arr = new List(Enum.GetValues(typeof(Animal)).Length);
step 4:
引入List之后发现无法使用原先的泛型工具方法,于是对其进行重载,但是返回只能使用object了
public static object RandomArray(Array arr)
{
Random random = new Random((int)DateTime.Now.Ticks);
int index = random.Next(0, arr.Length);
return arr.GetValue(index);
}
总结疑问:
疑问1:
如何将枚举类型直接转为枚举类型的数组?
疑问2:
得到Array类型之后如何向子类进行转换?



