How to Cast to Generic Parameter in C#? -
i'm trying write generic method fetching xelement value in strongly-typed fashion. here's have:
public static class xelementextensions { public static xelement getelement(this xelement xelement, string elementname) { // calls xelement.element(elementname) , returns xelement (with validation). } public static telementtype getelementvalue<telementtype>(this xelement xelement, string elementname) { xelement element = getelement(xelement, elementname); try { return (telementtype)((object) element.value); // first attempt. } catch (invalidcastexception originalexception) { string exceptionmessage = string.format("cannot cast element value '{0}' type '{1}'.", element.value, typeof(telementtype).name); throw new invalidcastexception(exceptionmessage, originalexception); } } } as can see on first attempt line of getelementvalue, i'm trying go string -> object -> telementtype. unfortunately, not work integer test case. when running following test:
[test] public void getelementvalueshouldreturnvalueofintegerelementasinteger() { const int expectedvalue = 5; const string elementname = "intprop"; var xelement = new xelement("name"); var integerelement = new xelement(elementname) { value = expectedvalue.tostring() }; xelement.add(integerelement); int value = xelementextensions.getelementvalue<int>(xelement, elementname); assert.areequal(expectedvalue, value, "expected integer value not returned element."); } i following exception when getelementvalue<int> called:
system.invalidcastexception : cannot cast element value '5' type 'int32'.
am going have handle each casting case (or @ least numeric ones) separately?
you try convert.changetype
convert.changetype(element.value, typeof(telementtype))
Comments
Post a Comment