[問題] 有關Activator.CreateInstance
這是MSDN上的範例:
Object o = Activator.CreateInstance(typeof(StringBuilder));
// Append a string into the StringBuilder object and display the
// StringBuilder.
StringBuilder sb = (StringBuilder) o;
sb.Append("Hello, there.");
Console.WriteLine(sb);
Activator.CreateInstance可以將Object o轉換成StringBuilder
然後還要將o轉型成StringBuilder, 才能呼叫sb.Append
我想問的問題是, 如果我有的資訊只有Type RRR, RRR可能是任何Type
Object o = Activator.CreateInstance(RRR);
但這樣我要怎樣才能把Object o轉換成RRR所代表的class,
不然我無法呼叫RRR包含的function, 謝謝~
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 118.168.21.72
→
07/07 17:43, , 1F
07/07 17:43, 1F
什麼意思啊? o.GetType() 拿到的值會等於 RRR
但還是不知道怎麼轉成RRR耶..
→
07/07 18:12, , 2F
07/07 18:12, 2F
→
07/07 18:12, , 3F
07/07 18:12, 3F
我舉個例子好了:
public class abc
{
public int init=0;
public int show()
{
return init;
}
}
string typename = abc.GetType().AssemblyQualifiedName;
這個typename字串儲存在檔案裡
Type ObjType = Type.GetType(typename);
這樣我會拿回abc的type, 到這裡ObjType = abc.getType();
object tempObj = Activator.CreateInstance(ObjType);
這樣會把object tempObj轉換成abc
這時如果我想call abc裡的show() or init變數, 一般做法是:
abc tempabc = (abc)tempObj;
然後再:
tempabc.show() or tempabc.init
但實際上到這裡知道的資訊, 只有從檔案取出來的typename轉換成ObjType
光是Type變數, 沒辦法讓tempObj轉型去呼叫show()
※ 編輯: xanlich 來自: 118.168.21.72 (07/07 18:25)
→
07/07 18:13, , 4F
07/07 18:13, 4F
→
07/07 18:14, , 5F
07/07 18:14, 5F
→
07/07 18:45, , 6F
07/07 18:45, 6F
那樣就變苦工了呀 XD, 我有100個class變成要寫100條判斷式
所以我上來問, 有沒有辦法在只有Type變數的情況可以轉型, 謝謝~
※ 編輯: xanlich 來自: 118.168.21.72 (07/07 18:51)
→
07/07 19:16, , 7F
07/07 19:16, 7F
→
07/07 19:17, , 8F
07/07 19:17, 8F
→
07/07 19:19, , 9F
07/07 19:19, 9F
推
07/07 21:34, , 10F
07/07 21:34, 10F