c# - Return typed object from method -
is there way make function return type of object pass in? call 1 method below return type pass in. possible? should trying this? there better way...short of having 2 different methods?
currently, tried first 2 calls , (with first call) looks dictionary system.object[] in value part of dictionary. screen shot below might show better explanation. ask might have more types need deserialize , don't want have different method each.
var firsttry = this.deserialize(path, typeof(observablecollection<listitempair>(); var secondtry = this.deserialize(path, typeof(listitempair)); var thirdtry = this.deserialize(path, typeof(someotherobject)); public static object deserialize(string jsonfile, object type) { var myobject = new object(); try { using (streamreader r = new streamreader(jsonfile)) { var serializer = new javascriptserializer(); string json = r.readtoend(); myobject = serializer.deserialize<object>(json); } } catch (exception ex) { } return myobject ; } public class listitempair { public string name { get; set; } public object value { get; set; } }
object created:
yes, can create generic method. deserialize()
method this:
public static t deserialize<t>(string jsonfile) { t myobject = default(t); try { using (var r = new streamreader(jsonfile)) { var serializer = new javascriptserializer(); string json = r.readtoend(); myobject = serializer.deserialize<t>(json); } } catch (exception ex) { } return myobject; }
in example t
type parameter. when invoking method, can pass type this:
var firsttry = deserialize<observablecollection<listitempair>>(path); var secondtry = deserialize<listitempair>(path); var thirdtry = deserialize<someotherobject>(path);
one side note: wouldn't recommend silently swallowing exception. in case, expected deserialization can fail. therefore, change trydeserialize()
method:
public static bool trydeserialize<t>(string jsonfile, out t myobject) { try { using (var r = new streamreader(jsonfile)) { var serializer = new javascriptserializer(); string json = r.readtoend(); myobject = serializer.deserialize<t>(json); } } catch (exception ex) { myobject = default(t); return false; } return true; }
Comments
Post a Comment