c# - 在 C# 中创建一个可以采用 double 、十进制和 float 而不重复代码的方法

标签 c# generics dry

我尽量避免不必要地重复代码。我有这个方法,我想根据基本计算返回 true 或 false。该值的参数可以是 doublefloatdecimal

这是我(失败的)尝试。任何指导将不胜感激。

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/

相关文章:

ios - Swift: 'Protocol'数组和实现类数组之间的转换

c - 避免重复/循环取消切换

c# - 使用 check C# 合并两个数据表

c# - 为什么对泛型的显式接口(interface)调用总是调用基础实现?

arrays - 使用随机数组字符串键入对象键/属性 - TypeScript

ruby-on-rails - 在 Rails 中处理 View 和仅助手常量的最佳方法

python - 使用 Python Enum 或 Dictionary 映射常量并通过推理保持 DRY 的最佳方法

c# - WPF 项目,使用按钮的侧边菜单导航

c# - 列表的排序包含具有字母/数字的字符串

c# - 如何在 C# 的集合中保存不同类型的对象?