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

可以返回值和引用类型对象的泛型函数

  •  4
  • Patrick  · 技术社区  · 14 年前

    我有一个helper函数从XML中获取值,它可以很好地处理int和string等值类型。我还有一些类在其构造函数中使用XPathNavigator作为参数,我想执行如下操作:

        public static void SelectSingleNodeSafe<T>(XPathNavigator nav, string pos, out T ret, T def)
        {
            XPathNavigator node = nav.SelectSingleNode(pos);
            if (node != null)
                if (typeof(T).IsSubclassOf(XMLConstructible))
                    ret = new T(node);// this won't compile
                else
                    ret = (T)node.ValueAs(typeof(T));//this works for my use cases
            else
                ret = def;
        }
    

    有志者事竟成?

    1 回复  |  直到 14 年前
        1
  •  6
  •   Logan Capaldo    14 年前

    new T 有一些编译时检查(显然如您所遇到的),但是您对它的使用是基于运行时信息的。即使您知道typeof(int).IsSubclassOf(XMLConstructible)永远不会为真,编译器也不会,因此 新T 不管你走不走这条路都要编译。而不是使用 新T ,使用反射创建实例。一个简单的方法是 Activator.CreateInstance

       ret = (T)Activator.CreateInstance(typeof(T), node); // this _will_ compile