C # type conversion,

Source: Internet
Author: User

C # type conversion,

A common type conversion is not easy. If you get the UI data during development or retrieve the data from the database (not Using ORM), The type conversion is very cumbersome, I have written very ugly type conversion code. The following code is slightly better and can also be used in automatic object ing.

Type conversion code

1 public class TypeHelper 2 {3 // <summary> 4 // it should only be used to convert the basic type 5 /// </summary> 6 /// <param name =" value "> </param> 7 // <param name =" type "> </param> 8 // <param name =" defaultVal "> </param> 9 /// <returns> </returns> 10 public static object ChangeType (object value, type type, object defaultVal = null) 11 {12 // no input type, 13 if (Type = null) return value; 14 15 // no input conversion value, the default value of the return type is 16 if (value = n Ull) return getdefavalue value (type); 17 18 // type consistency does not need to be converted 19 if (value. getType () = type) return value; 20 21 // Nullable type, convert the type to the actual type 22 if (type. isGenericType & type. getGenericTypeDefinition () = typeof (Nullable <>) 23 {24 type = type. getGenericArguments () [0]; 25} 26 27 // Enumeration type processing 28 if (type. isEnum) return ConvertToEnum (value, type); 29 30 // handle 31 if (value is string & type = typeof (GUID) 32 {33 Guid; 34 guid. tryParse (value as string, out guid); 35 return guid; 36} 37 38 // increase in bool type and int type conversion processing 39 if (type = typeof (bool )) 40 {41 int I; 42 if (TryConvertToInt (value, out I) 43 {44 value = I! = 0; 45} 46} 47 48 // other conversions 49 try 50 {51 return System. convert. changeType (value, type); 52} 53 catch 54 {55 return defaultVal ?? GetDefaultValue (type); 56} 57} 58 59 public static T convertize <T> (object obj, T defalutValue = default (T) 60 {61 return (T) TypeHelper. changeType (obj, typeof (T), defalutValue); 62} 63 64 private static bool TryConvertToInt (object value, out int result) 65 {66 try 67 {68 result = (int) system. convert. changeType (value, typeof (int); 69 return true; 70} 71 catch 72 {73 result = default (int); 7 4 return false; 75} 76} 77 78 private static object ConvertToEnum (object value, Type type) 79 {80 if (value is string) 81 {82 try 83 {84 return Enum. parse (type, value as string); 85} 86 catch 87 {88 return Activator. createInstance (type); 89} 90} 91 else 92 {93 return Enum. toObject (type, value); 94} 95} 96 97 private static object GetDefaultValue (Type type) 98 {99 if (! Type. IsValueType) return null; 100 101 if (! _ Defavaluvalues. containsKey (type) 102 _ defaultValues [type] = Activator. createInstance (type); 103 104 return _ defavaluvalues [type]; 105} 106 107 private static readonly Dictionary <Type, object> _ defaultValues = new Dictionary <Type, object> (); 108}

Test code

 1     [TestClass()] 2     public class TypeHelperTest 3     { 4         [TestMethod] 5         public void NormalTest() 6         { 7             Assert.AreEqual('1', TypeHelper.ChangeType("1", typeof(char))); 8             Assert.AreEqual(10, TypeHelper.ChangeType("10", typeof(int))); 9             Assert.AreEqual(10m, TypeHelper.ChangeType("10", typeof(decimal)));10         }11 12         [TestMethod]13         public void NullArgumentTest()14         {15             Assert.AreEqual(null, TypeHelper.ChangeType(null, null));16             Assert.AreEqual(0, TypeHelper.ChangeType(null, typeof(int)));17             Assert.AreEqual(0m, TypeHelper.ChangeType(null, typeof(decimal)));18             Assert.AreEqual(null, TypeHelper.ChangeType(null, typeof(string)));19             Assert.AreEqual("10", TypeHelper.ChangeType("10", null));20             Assert.AreEqual(10, TypeHelper.ChangeType(10, null));21         }22 23         [TestMethod]24         public void NullableTypeTest()25         {26             Assert.AreEqual(null, TypeHelper.ChangeType(null, typeof(int?)));27             Assert.AreEqual(10, TypeHelper.ChangeType("10", typeof(int?)));28         }29 30         [TestMethod]31         public void BoolTypeTest()32         {33             Assert.AreEqual(true, TypeHelper.ChangeType("true", typeof(bool)));34             Assert.AreEqual(false, TypeHelper.ChangeType("false", typeof(bool)));35 36             Assert.AreEqual(true, TypeHelper.ChangeType("TRUE", typeof(bool)));37             Assert.AreEqual(false, TypeHelper.ChangeType("FALSE", typeof(bool)));38 39             Assert.AreEqual(true, TypeHelper.ChangeType("1", typeof(bool)));40             Assert.AreEqual(false, TypeHelper.ChangeType("0", typeof(bool)));41 42             Assert.AreEqual(true, TypeHelper.ChangeType(1, typeof(bool)));43             Assert.AreEqual(false, TypeHelper.ChangeType(0, typeof(bool)));44 45             Assert.AreEqual(true, TypeHelper.ChangeType("11", typeof(bool)));46             Assert.AreEqual(true, TypeHelper.ChangeType("-1", typeof(bool)));47         }48 49         [TestMethod]50         public void EnumTypeTest()51         {52             Assert.AreEqual(TestEnum.A, TypeHelper.ChangeType(1, typeof(TestEnum)));53             Assert.AreEqual(TestEnum.A, TypeHelper.ChangeType("1", typeof(TestEnum)));54             Assert.AreEqual(TestEnum.A, TypeHelper.ChangeType("A", typeof(TestEnum)));55             Assert.AreEqual((TestEnum)0, TypeHelper.ChangeType("a", typeof(TestEnum)));56         }57 58         [TestMethod]59         public void GuidTypeTest()60         {61             Assert.AreEqual(Guid.Empty, TypeHelper.ChangeType(null, typeof(Guid)));62             Assert.AreEqual(Guid.Empty, TypeHelper.ChangeType("dfdsfs", typeof(Guid)));63             Assert.AreEqual(new Guid("{244F8EE2-DDD3-486A-B3E7-9EFDEEE4488C}"), TypeHelper.ChangeType("{244F8EE2-DDD3-486A-B3E7-9EFDEEE4488C}", typeof(Guid)));64         }65     }66 67     public enum TestEnum68     {69         A = 1, B = 270     }71 }

 


A simple program of C language Bubble Sorting

Main ()
{
Int I, j, temp;
Int a [10];
For (I = 0; I <10; I ++)
Scanf ("% d,", & a [I]);
For (j = 0; j <= 9; j ++)
{For (I = 0; I <10-j; I ++)
If (a [I]> a [I + 1])
{Temp = a [I];
A [I] = a [I + 1];
A [I + 1] = temp ;}
}
For (I = 1; I <11; I ++)
Printf ("% 5d,", a [I]);
Printf ("\ n ");
}

--------------
Bubble Algorithm
Algorithm Analysis and Improvement of Bubble Sorting
The basic idea of exchanging sorting is to compare the keywords of the records to be sorted in pairs. If the order of the two records is the opposite, the two records are exchanged until there is no reverse order record.
The basic concepts of application exchange sorting include Bubble sorting and quick sorting.

Bubble Sorting

1. Sorting Method
Vertically arrange the sorted record array R [1. n]. Each record R is considered as a bubble with the weight of R. key. According to the principle that a Light Bubble cannot be under a heavy bubble, scan the array R from the bottom up: Any Light Bubble scanned to a violation of this principle will make it "float" up ". This is repeated until the last two bubbles are light and heavy.
(1) initial
R [1. n] is an unordered area.

(2) First scan
The weights of two adjacent bubbles are compared from the bottom of the unordered area to the top. If the light bubbles are found to be in the lower and severe bubbles, the positions of the two bubbles are exchanged. That is, compare (R [n], R [n-1]), (R [n-1], R [N-2]),…, (R [2], R [1]); for each pair of bubbles (R [j + 1], R [j]), if R [j + 1]. key <R [j]. key, then the contents of R [j + 1] and R [j] are exchanged.
When the first scan is complete, the "lightest" bubble floated to the top of the interval, that is, the record with the smallest keyword is placed on the highest position R [1.

(3) second scan
Scan R [2. n]. When scanning is completed, the "light" bubble floated to the R [2] position ......
Finally, the sequential area R [1. n] can be obtained through n-1 scanning.
Note:
During the I-trip scan, R [1 .. I-1] and R [I.. n] are the current sequential and disordered areas, respectively. The scan continues from the bottom of the unordered area to the top of the area. When scanning is completed, the shortest bubbles in the area float to the top position R. The result is that R [1. I] is changed to a new ordered area.

2. Bubble sorting process example
Bubble Sorting of files whose keyword sequence is 49 38 65 97 76 13 27 49

3. Sorting Algorithm
(1) Analysis
Because each sort adds a bubble to the ordered area, there are n-1 bubbles in the ordered area after N-1 sort, in the disordered area, the bubble weight is always greater than or equal to the bubble weight in the ordered area. Therefore, the entire Bubble sorting process requires at most n-1 sorting.
If no bubble position exchange is found in a sorting, it means that all bubbles in the unordered area to be sorted meet the principle of being light and heavy. Therefore, the Bubble sorting process can be terminated after this sorting. Therefore, in the following algorithm, a Boolean exchange is introduced, which is set to FALSE before each sort starts. If an exchange occurs during the sorting process, set it to TRUE. Check exchange at the end of sorting. If exchange has not occurred, terminate the algorithm and no longer perform the next sorting.

(2) specific algorithms
Void BubbleSort (SeqList R)
{// R (l. n) is the file to be sorted. It uses bottom-up scanning to perform Bubble Sorting on R.
Int I, j;
Boolean exchange; // exchange flag
For (I = 1; I <G id = "1">

A simple program of C language Bubble Sorting

Main ()
{
Int I, j, temp;
Int a [10];
For (I = 0; I <10; I ++)
Scanf ("% d,", & a [I]);
For (j = 0; j <= 9; j ++)
{For (I = 0; I <10-j; I ++)
If (a [I]> a [I + 1])
{Temp = a [I];
A [I] = a [I + 1];
A [I + 1] = temp ;}
}
For (I = 1; I <11; I ++)
Printf ("% 5d,", a [I]);
Printf ("\ n ");
}

--------------
Bubble Algorithm
Algorithm Analysis and Improvement of Bubble Sorting
The basic idea of exchanging sorting is to compare the keywords of the records to be sorted in pairs. If the order of the two records is the opposite, the two records are exchanged until there is no reverse order record.
The basic concepts of application exchange sorting include Bubble sorting and quick sorting.

Bubble Sorting

1. Sorting Method
Vertically arrange the sorted record array R [1. n]. Each record R is considered as a bubble with the weight of R. key. According to the principle that a Light Bubble cannot be under a heavy bubble, scan the array R from the bottom up: Any Light Bubble scanned to a violation of this principle will make it "float" up ". This is repeated until the last two bubbles are light and heavy.
(1) initial
R [1. n] is an unordered area.

(2) First scan
The weights of two adjacent bubbles are compared from the bottom of the unordered area to the top. If the light bubbles are found to be in the lower and severe bubbles, the positions of the two bubbles are exchanged. That is, compare (R [n], R [n-1]), (R [n-1], R [N-2]),…, (R [2], R [1]); for each pair of bubbles (R [j + 1], R [j]), if R [j + 1]. key <R [j]. key, then the contents of R [j + 1] and R [j] are exchanged.
When the first scan is complete, the "lightest" bubble floated to the top of the interval, that is, the record with the smallest keyword is placed on the highest position R [1.

(3) second scan
Scan R [2. n]. When scanning is completed, the "light" bubble floated to the R [2] position ......
Finally, the sequential area R [1. n] can be obtained through n-1 scanning.
Note:
During the I-trip scan, R [1 .. I-1] and R [I.. n] are the current sequential and disordered areas, respectively. The scan continues from the bottom of the unordered area to the top of the area. When scanning is completed, the shortest bubbles in the area float to the top position R. The result is that R [1. I] is changed to a new ordered area.

2. Bubble sorting process example
Bubble Sorting of files whose keyword sequence is 49 38 65 97 76 13 27 49

3. Sorting Algorithm
(1) Analysis
Because each sort adds a bubble to the ordered area, there are n-1 bubbles in the ordered area after N-1 sort, in the disordered area, the bubble weight is always greater than or equal to the bubble weight in the ordered area. Therefore, the entire Bubble sorting process requires at most n-1 sorting.
If no bubble position exchange is found in a sorting, it means that all bubbles in the unordered area to be sorted meet the principle of being light and heavy. Therefore, the Bubble sorting process can be terminated after this sorting. Therefore, in the following algorithm, a Boolean exchange is introduced, which is set to FALSE before each sort starts. If an exchange occurs during the sorting process, set it to TRUE. Check exchange at the end of sorting. If exchange has not occurred, terminate the algorithm and no longer perform the next sorting.

(2) specific algorithms
Void BubbleSort (SeqList R)
{// R (l. n) is the file to be sorted. It uses bottom-up scanning to perform Bubble Sorting on R.
Int I, j;
Boolean exchange; // exchange flag
For (I = 1; I <G id = "1">

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.