[問題] 請問要怎麼寫呢?

看板C_Sharp作者 (血腹獸)時間15年前 (2008/10/09 13:37), 編輯推噓3(304)
留言7則, 5人參與, 最新討論串1/1
假設有一個存在的Class A Class A { public string str1; public string str2; public string str3; . . . } 在另一個class中 使用System.Collection的類別來儲存Class A 如 List<A> aList = new List<A>(); 在aList中存了許多A的實例,且屬性的值都不一樣 今天有可能作一個靜態方法印出在List中某個特定的屬性的字串嗎? 像是 指定的屬性 ↓↓ public static string printSpecialFieldAcrossList(List<A> list, ????, string separator) { } 我會的方法只有把屬性寫死進去,如: 把List中每個實例的Str1印出來 public static string printStr1AccrossList(List<A> list, string separator) { string retStr = ""; IEnumrator iterator = list.GetEnumerator(); while(iterator.MoveNext()) { A a = iterator.Current; // 這裡的a.Str1,只是舉例 retStr = retStr + a.str1 + separator; } return retStr; } 這種寫法雖然能做到 但是問題是,只要A的屬性有十種,我就必須寫十種這種行為幾乎完全相同的method 差別只有在a.str1時叫用別的屬性可能是 a.str2 或 a.str3 所以想請教各位板友 有沒有能在method中同時指定是什麼屬性的方法 不好意思問題很長,謝謝各位板友 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 61.56.13.124 ※ 編輯: kairy 來自: 61.56.13.124 (10/09 13:42)

10/09 13:47, , 1F
public static object func( -, type T, -) ?
10/09 13:47, 1F

10/09 14:38, , 2F
Type的GetProperty 方法
10/09 14:38, 2F

10/09 15:09, , 3F
可以找找C++中有關function template的資訊..
10/09 15:09, 3F

10/09 15:10, , 4F
Sorry..這是C#版, C#中有支援class template(叫泛型)..但
10/09 15:10, 4F

10/09 15:11, , 5F
是有沒有支援function template要再查查..
10/09 15:11, 5F

10/09 15:45, , 6F
唔~我還是不太了解怎麼做,可以再細節一點嗎?
10/09 15:45, 6F

10/09 20:43, , 7F
2樓的方法就可以知道你這個物件的內容了
10/09 20:43, 7F
文章代碼(AID): #18xPYeCa (C_Sharp)