Last week the code encountered a problem, because of design constraints, a method accepts parameters only list<object> type, but the method needs to deal with the real data is determined list<currency>. However, C # does not allow a direct conversion type to be displayed and is not operable in two directions. The problem blew me off for a while, and finally, on MSDN, I found a oftype<t> way to do it.
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;namespaceconsoleapplication1{Internal classProgram {Private Static voidMain (string[] args) {List<Object> Currencylistoftype =Newlist<Object>() { NewCurrency () {Id = Guid.NewGuid (), Name ="a"}, NewCurrency () {Id = Guid.NewGuid (), Name ="b"}, NewCurrency () {Id = Guid.NewGuid (), Name ="C"} }; List<Object> currencylistcast =Newlist<Object>() { "a","b","C" }; //=>oftype If the element is not converted, the exception is not present, only the successful element is converted, or the list is empty if the currencies is not converted, NOT NULLList<currency> currencies = currencylistoftype.oftype<currency>(). ToList (); //=>cast If the element cannot be converted, it will fail. list<currency> currencies1 = currencylistcast.cast<currency>(). ToList (); Console.WriteLine ("Currencies List:"); foreach(varIteminchcurrencies) {Console.WriteLine (item. ID); } Console.WriteLine ("currencies1 list:"); foreach(varIteminchcurrencies1) {Console.WriteLine (item. ID); } console.readline (); } } Public classCurrency { PublicGuid Id {Get;Set; } Public stringName {Get;Set; } }}
How C # Converts list of object to list of T concrete types