Sometimes we suddenly use some rare usage when writing a program. For example, we encountered such a problem during programming today. I have never encountered this problem before. I don't know how to solve it at the beginning. In the search process, it is found that the. net class library has provided a ready-made processing method. Therefore, we will record it here for future reference only and hope to have a reference for a friend who needs the same. Let's take a look at this problem!
Problem description:A generic method, such as public List <T> getList <T> (), returns a List set. The element type in the List set is specified when the generic method is called. In the specific implementation of the getList method, some types of data may need to be converted to the T type, and then added to the List set.
Example:Call the getList <int> () method. The data is of the string type. Therefore, you must convert the string type to the int type before adding the data to the List <int> set.
Solution:
Under the namespace System, we found a ChangeType method under the Convert class, which has three reload methods, as shown in:
For more information about this method, see MSDN: http://technet.microsoft.com/zh-cn/library/system.convert.changetype (en-us). aspx
With this method, let's take a look at how to solve this problem.
- Obtain the System. Type object of generic Type T, and use typeof (T ).
- Use the Convert. ChangeType method to Convert a String to an object equivalent to a T object.
- Convert the obtained object to T.
You can extract the above process into a public method and look at the following code.
01
public
static
T FromType<T,TK>(TK text)
02
{
03
try
04
{
05
return
(T) Convert.ChangeType(text,
typeof
(T), CultureInfo.InvariantCulture);
06
}
07
catch
08
{
09
return
default
(T);
10
}
11
}