作者kairy (血腹獸)
看板C_Sharp
標題[問題] 請問要怎麼寫呢?
時間Thu Oct 9 13:37:41 2008
假設有一個存在的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)
1F:→ hpo14:public static object func( -, type T, -) ? 10/09 13:47
2F:→ O2000:Type的GetProperty 方法 10/09 14:38
3F:推 horngsh:可以找找C++中有關function template的資訊.. 10/09 15:09
4F:推 horngsh:Sorry..這是C#版, C#中有支援class template(叫泛型)..但 10/09 15:10
5F:→ horngsh:是有沒有支援function template要再查查.. 10/09 15:11
6F:→ kairy:唔~我還是不太了解怎麼做,可以再細節一點嗎? 10/09 15:45
7F:推 help0430:2樓的方法就可以知道你這個物件的內容了 10/09 20:43