代码之家  ›  专栏  ›  技术社区  ›  dav

C#类型转换泛型引用参数

  •  0
  • dav  · 技术社区  · 16 年前

    我怎么才能让它工作呢?正在使用泛型类型将结果更新为100。有什么想法吗?当然这个功能还没有完成,我只需要让结果功能正常工作,这样我就可以继续。

        public static bool ReadMemory<T>(Process process, IntPtr address, ref T result)
        {
            Type objType = result.GetType();
    
            switch (objType.Name)
            {
                case "Int32":
                    result = (T)100;
                    return true;
                default:
                    return false;
            }
        }
    
    2 回复  |  直到 16 年前
        1
  •  1
  •   Paul Sasik    16 年前

    我会重构这个并返回结果。如果开关或if/else锁掉到方法的底部,我将抛出异常。然后可以在客户机代码中的try/catch中捕获失败。

        2
  •  0
  •   raptoravis    9 年前

    你只需要把它特殊化为类型:

    public static bool ReadMemory(Process process, IntPtr address, ref int result)
    {
       result = 100;
       return true;
    }
    
    public static bool ReadMemory(Process process, IntPtr address, ref float result)
    {
       result = 100.0f;
       return true;
    }