通過Emit實現動態類生成

2021-09-05 18:57:52 字數 1199 閱讀 6965

麻煩歸麻煩,非不能也,動態生成乙個簡單的類還不至於太難。

假設有如下介面:

inte***ce ianimal

希望能建立乙個類生成器typecreator,並能以以下方式使用:

typecreator tc=new typecreator(typeof(ianimal));

type t = tc.build();

ianimal myanimal= (ianimal)activator.createinstance(t);

myanimal.move();

myanimal.eat();

using system;

using system.reflection;

using system.reflection.emit;

public class typecreator

public type build() ;

} else

//得到型別生成器

typebuilder typebuilder = modbuilder.definetype(newtypename,newtypeattribute,newtypeparent,newtypeinte***ces);

//以下將為新型別宣告方法:新型別應該override基型別的所以virtual方法

//得到基型別的所有方法

methodinfo targetmethods = targettype.getmethods();

//遍歷各個方法,對於virtual的方法,獲取其簽名,作為新型別的方法

foreach(methodinfo targetmethod in targetmethods)

ilgen.emit(opcodes.ldstr,"i'm "+ targetmethod.name +"ing");

ilgen.emit(opcodes.call,typeof(console).getmethod("writeline",new type));

ilgen.emit(opcodes.ret); }

} //真正建立,並返回

return(typebuilder.createtype()); }

} 好了,測試一下試試看:using system;

public class tester

}

通過Emit實現動態類生成

麻煩歸麻煩,非不能也,動態生成乙個簡單的類還不至於太難。假設有如下介面 inte ce ianimal 希望能建立乙個類生成器typecreator,並能以以下方式使用 typecreator tc new typecreator typeof ianimal type t tc.build ian...

動態生成CS檔案(動態生成C 類)

1.codetypedeclaration 可用於表示宣告類 結構 介面或列舉的 官方傳送門 2.codememberfield 表示某種型別的字段的宣告 官方傳送門 3.codedomprovider 可用於建立和檢索 生成器和 編譯器的例項。生成器可用於以特定的語言生成 而 編譯器可用於將 編譯...

vue通過 emit傳值的方式實現簡單的搜尋功能

1 首先先專案中建立乙個檔案,該檔案隨便起名sousuo.vue html sousuo t sousuo keyup.enter searchcont el icon search i t sousuo xiao text placeholder 請輸入內容 ref input v model s...