Generic function which can return value and reference type objects
I've got a helper function to get values from XML which works fine with value types like ints and also strings. I also have some classes which take an XPathNavigator as a parameter in their constructors and I'd like to do something like the following:
public static void SelectSingleNodeSafe<T>(XPathNavigator nav, string pos, out T ret, T def)
{
XPathNav开发者_运维技巧igator 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;
}
There is a will but is there a way?
new T
has some compile time checks (obviously as you've run into), but your use of it is based on run-time information. Even though you know typeof(int).IsSubclassOf(XMLConstructible)) will never be true, the compiler doesn't, so the new T
has to compile whether you go down that path or not. Instead of using new T
, use reflection to create the instance. An easy way is to use Activator.CreateInstance
ret = (T)Activator.CreateInstance(typeof(T), node); // this _will_ compile
精彩评论