[請益] 關於.net技術問題
各位大家好,今天有一個小小想法。
時常我們在處理字串時,常常會去空格或空白。
假設我有一個Class 裡面的屬於String 的Property的值都要去空白。
我靠著這篇討論寫出來,http://ppt.cc/l8pY
以下討論內容不考慮實務上的合理性,僅探討程式碼。
畢竟實務真的這樣寫也太奇怪。
圖文版:http://ppt.cc/CLoU
寫法大概是:
foreach (var property in MyClass.GetType().GetProperties())
{
if (property.PropertyType.ToString() == "System.String")
property.SetValue(MyClass, property.GetValue(MyClass, null).ToString().Replace(" ", ""), null);
}
我想把它包成一個Function,寫成:
private static object TrimSpace(object MyClass)
{
foreach (var property in MyClass.GetType().GetProperties())
{
if (property.PropertyType.ToString() == "System.String")
property.SetValue(MyClass, property.GetValue(MyClass, null).ToString().Replace(" ", ""), null);
}
return MyClass;
}
可是,這樣會是一個object,感覺不太好。
又看了看那篇文章,寫出另外一種方法:
public class ClassFix<T> where T : class
{
public static T StringReplaceSpace(T oObj)
{
foreach (var property in oObj.GetType().GetProperties())
{
if (property.PropertyType.ToString() == "System.String")
property.SetValue(oObj, property.GetValue(oObj, null).ToString().Replace(" ", ""), null);
}
return oObj;
}
}
寫這麼多,問題來了。
我雖然寫出最後一段,可是我卻完全不了解為何。
想請大家看有沒有甚麼可以搜尋相關資訊的建議或方向。
我不了解的點:
1.public class ClassFix<T> where T :class
這樣的寫法應該要怎麼用言語解釋?
不知道<T>這樣到底是怎麼樣去說明。
2.最後那段寫法,算是一個Function嗎?還是,屬於一種擴充?
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 123.194.233.173
→
01/21 23:03, , 1F
01/21 23:03, 1F
→
01/21 23:04, , 2F
01/21 23:04, 2F
→
01/21 23:05, , 3F
01/21 23:05, 3F
→
01/21 23:06, , 4F
01/21 23:06, 4F
→
01/21 23:10, , 5F
01/21 23:10, 5F
→
01/21 23:10, , 6F
01/21 23:10, 6F
→
01/21 23:34, , 7F
01/21 23:34, 7F
→
01/21 23:35, , 8F
01/21 23:35, 8F
→
01/21 23:37, , 9F
01/21 23:37, 9F
→
01/21 23:39, , 10F
01/21 23:39, 10F
→
01/21 23:40, , 11F
01/21 23:40, 11F
→
01/21 23:41, , 12F
01/21 23:41, 12F
→
01/21 23:44, , 13F
01/21 23:44, 13F
推
01/22 00:13, , 14F
01/22 00:13, 14F
推
01/22 00:18, , 15F
01/22 00:18, 15F
→
01/22 05:35, , 16F
01/22 05:35, 16F
→
01/22 08:48, , 17F
01/22 08:48, 17F
→
01/22 09:28, , 18F
01/22 09:28, 18F
→
01/22 10:16, , 19F
01/22 10:16, 19F
推
01/22 16:52, , 20F
01/22 16:52, 20F
→
01/22 16:53, , 21F
01/22 16:53, 21F
→
01/23 11:51, , 22F
01/23 11:51, 22F