THY02K
January 24th, 2009, 10:26 PM
I was having problem (see below "TROUBLE") casting int/double to generics ... This is what I intended to write,
public T RecursiveGetNextRandom<T>(T Max, T Min, List<T> lstExcludedNum)
{
int nNextNum = 0;
double dbNextNum 0;
T NextNum;
nMin = Convert.ToInt32(Min);
nMax = Convert.ToInt32(Max);
nNextNum = oRand.Next(nMin, nMax);
if(Max is double)
{
dbNextNum = oRand.NextDouble() * nNextNum;
NextNum = (T) dbNextNum; << TROUBLE: Can't cast to <T>!
} else if (Max is int) {
NextNum = (T) nNextNum; << TROUBLE: Can't cast to <T>!
}
return NextNum;
}
I ended up writing the following ugly code:
public static object RecursiveGetNextRandom(object Max, object Min, ArrayList lstExcludedNum)
{
object NextNum = 0;
Random oRand = new Random(Guid.NewGuid().GetHashCode());
double dbMin;
double dbMax;
int nNextNum;
if (Min == null)
{
Min = Int32.MinValue;
}
if (Max == null)
{
Max = Int32.MaxValue;
}
if (!(Max is int || Max is double))
{
...
}
dbMin = Convert.ToInt32(Min);
dbMax = Convert.ToInt32(Max);
SwapIfGreater(ref dbMin, ref dbMax);
nNextNum = oRand.Next(Convert.ToInt32(Math.Floor(dbMin)), Convert.ToInt32(Math.Floor(dbMax)));
if (Max is double)
{
NextNum = (double)nNextNum * oRand.NextDouble();
}
else if (Max is int)
{
NextNum = (int)nNextNum;
}
if (lstExcludedNum != null)
{
if (lstExcludedNum.Contains(NextNum))
{
RecursiveGetNextRandom(Max, Min, lstExcludedNum);
}
}
return NextNum;
}
Any suggestion? Thanks!~
public T RecursiveGetNextRandom<T>(T Max, T Min, List<T> lstExcludedNum)
{
int nNextNum = 0;
double dbNextNum 0;
T NextNum;
nMin = Convert.ToInt32(Min);
nMax = Convert.ToInt32(Max);
nNextNum = oRand.Next(nMin, nMax);
if(Max is double)
{
dbNextNum = oRand.NextDouble() * nNextNum;
NextNum = (T) dbNextNum; << TROUBLE: Can't cast to <T>!
} else if (Max is int) {
NextNum = (T) nNextNum; << TROUBLE: Can't cast to <T>!
}
return NextNum;
}
I ended up writing the following ugly code:
public static object RecursiveGetNextRandom(object Max, object Min, ArrayList lstExcludedNum)
{
object NextNum = 0;
Random oRand = new Random(Guid.NewGuid().GetHashCode());
double dbMin;
double dbMax;
int nNextNum;
if (Min == null)
{
Min = Int32.MinValue;
}
if (Max == null)
{
Max = Int32.MaxValue;
}
if (!(Max is int || Max is double))
{
...
}
dbMin = Convert.ToInt32(Min);
dbMax = Convert.ToInt32(Max);
SwapIfGreater(ref dbMin, ref dbMax);
nNextNum = oRand.Next(Convert.ToInt32(Math.Floor(dbMin)), Convert.ToInt32(Math.Floor(dbMax)));
if (Max is double)
{
NextNum = (double)nNextNum * oRand.NextDouble();
}
else if (Max is int)
{
NextNum = (int)nNextNum;
}
if (lstExcludedNum != null)
{
if (lstExcludedNum.Contains(NextNum))
{
RecursiveGetNextRandom(Max, Min, lstExcludedNum);
}
}
return NextNum;
}
Any suggestion? Thanks!~