我尽量避免不必要地重复代码。我有这个方法,我想根据基本计算返回 true 或 false。该值的参数可以是 double
、float
、decimal
。
这是我(失败的)尝试。任何指导将不胜感激。
private bool DoMyThingGeneric(Type type, object value)
{
// I'm trying to do something like this:
// cast "value" to "type"
var constructed = type.MakeGenericType();
object obj = Activator.CreateInstance(constructed);
// assign "value" to "d" - THIS DOESN'T WORK
var endVal = obj as typeof(type);
if (Math.Floor(endVal * 1000) == endVal * 1000)
{
return true;
}
return false;
}
private bool DoMyThing(decimal x)
{
DoMyThingGeneric(x.GetType(), x);
return false;
}
private bool DoMyThing(float x)
{
DoMyThingGeneric(x.GetType(), x);
return false;
}
private bool DoMyThing(double x)
{
DoMyThingGeneric(x.GetType(), x);
return false;
}
最佳答案
重复代码。或类型转换。
因为泛型不能有运算符....没有替代方案。
关于c# - 在 C# 中创建一个可以采用 double 、十进制和 float 而不重复代码的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22261510/