Re: [問題] ref跟指標

作者: erspicu (.)   2018-03-20 22:10:10
※ 引述《justinj (黑旋風)》之銘言:
: public struct AAA
: {
: public string BBB;
: public string BBB2;
: public string BBB3;
: public string BBB4;
: }
: public struct CCC
: {
: public AAA C1;
: public AAA C2;
: public AAA C3;
: public AAA C4;
: public AAA C5;
: }
: public static void func(ref CCC data,int a)
: {
: AAA[] loc_data=new AAA[]
: {
: data.C1,data.C2,data.C3,data.C4,data.C5
: };
: if(a<5 && a>=0)
: {
: loc_data[a].BBB="test1";
: }
: }
: ===============================================
: 請問一下C#有沒有法子做到類似指標的動作,
: 目前想不到在函數內將資料設定進去的方法
可以用全C指標的寫法 來達成 不過很怪異
按照你的需求 有更快的作法是 set 或是 get field by name
利用 reflection 就可以 google 關鍵字 c# struct set filed reflection
參考 https://tinyurl.com/yas7rmoy
基本上可以改成
if(a<5 && a>=0)
{
設定 data 裡頭 一個名為 "C"+a.ToString() 的 filed 內容成 test1
}
reflection平常用不到不知道哪裡好用也不知道作啥用的
用到時候才覺得真是好物
作者: Litfal (Litfal)   2018-03-20 23:23:00
反射其中之一的用途,就是用來做一些感覺手作很蠢的事
作者: justinj (黑旋風)   2018-03-21 11:23:00
謝謝提供
作者: ssccg (23)   2018-03-21 11:30:00
reflection本來就慢了,配struct還要box unbox copy...如果不是真的field太多,我是會選比較蠢的手作法啦..當然實際上要看原po的應用場景這邊需不需要考量效能

Links booklink

Contact Us: admin [ a t ] ucptt.com