public static void GenerateRandomd<T>(D_List<T> list, int size, Random rand)
{
if (list is D_List<int>)
{
for (int i = 0; i < size; i++)
list.Push_Back(rand.Next(0, 10000));
}
else if (list is D_List<string>)
{
for (int i = 0; i < size; i++)
list.Push_Back(Gen_rand_string(rand));
}
else
{
for (int i = 0; i < size; i++)
list.Push_Back(rand.NextDouble());
}
}
你好!有可能实现这样的东西吗?提前谢谢。
您只需要通过模式匹配来强制转换list
变量:
public static void GenerateRandomd<T>(D_List<T> list, int size, Random rand)
{
switch (list)
{
case D_List<int> il:
for (int i = 0; i < size; i++)
il.Push_Back(rand.Next(0, 10000));
break;
case D_List<string> sl:
for (int i = 0; i < size; i++)
sl.Push_Back(Gen_rand_string(rand));
break;
default:
for (int i = 0; i < size; i++)
(list as D_List<double>).Push_Back(rand.NextDouble());
}
}
或者你可以直接在你的代码中投射它:
public static void GenerateRandomd<T>(D_List<T> list, int size, Random rand)
{
if (list is D_List<int>)
{
for (int i = 0; i < size; i++)
(list as DList<int>).Push_Back(rand.Next(0, 10000)); // cast variable to the DList<int> at each step of the cyclecast
}
else if (list is D_List<string>)
{
for (int i = 0; i < size; i++)
(list is D_List<string>).Push_Back(Gen_rand_string(rand));
}
else
{
for (int i = 0; i < size; i++)
(list is D_List<double>).Push_Back(rand.NextDouble());
}
}
如果默认场景意味着不同的类型,那么您可以为D_List
实现非通用的Push_Back(double value)
方法。