gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:57:48 25 4
gpt4 key购买 nike

我有一个辅助函数可以从 XML 中获取值,它可以很好地处理值类型,例如 int 和字符串。我还有一些类在其构造函数中将 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;
}

有志但有办法吗?

最佳答案

new T 有一些编译时检查(很明显,正如您遇到的那样),但您对它的使用是基于运行时信息。即使您知道 typeof(int).IsSubclassOf(XMLConstructible)) 永远不会为真,但编译器不会,因此无论您是否沿着这条路走下去,new T 都必须编译。不使用 new T,而是使用反射来创建实例。一种简单的方法是使用 Activator.CreateInstance

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

关于c# - 可以返回值和引用类型对象的泛型函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4305126/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com