我正在尝试创建一个Generic类来处理float和double。我需要根据变量的类型(float或double)执行计算,但我不确定以下实现是否是正确的方法。需要一些建议。
// computeFloat is a method of some other class which actually computes and returns a float value
float computeFloat()
{
float a;
....
return a;
}
// setFloat is a method of some other class which actually sets a float value
void setFloat(float val)
{
.....
}
TestClass<T> : IDisposable
{
public void getValue(ref T val)
{
if(val is float)
{
object retVal = computeFloat();
val = (float)retVal;
}
else
{
throw new Exception(" Not implemented");
}
}
public void setValue(T val)
{
if(val is float)
{
object obj = val as object;
float retVal = (float)obj;
setFloat(retVal);
}
else
{
throw new Exception(" Not implemented");
}
}
}
答案 0 :(得分:1)
您可以查看以下内容以避免if语句。您还可以考虑在类上添加过滤器以将其限制为某些类型。
public void getValue(ref T val)
{
object retVal = compute<T>();
val = (T)retVal;
}