魯迪格的答案是接近,但需要一些小的修改,以實際生成請求的代碼:
CSharpCodeProvider codeProvider = new CSharpCodeProvider();
CodeCompileUnit compileUnit = new CodeCompileUnit();
CodeNamespace nameSpace = new CodeNamespace("xy");
compileUnit.Namespaces.Add(nameSpace);
CodeTypeDeclaration myClass = new CodeTypeDeclaration("MyClass");
nameSpace.Types.Add(myClass);
myClass.TypeAttributes = System.Reflection.TypeAttributes.Class | System.Reflection.TypeAttributes.Public;
CodeTypeReference dictionaryType = new CodeTypeReference("IDictionary", new CodeTypeReference(typeof(string)), new CodeTypeReference(typeof(Type)));
CodeMemberField myClass_databaseAccessClasses = new CodeMemberField(dictionaryType, "databaseAccessClasses");
myClass_databaseAccessClasses.Attributes = MemberAttributes.Static | MemberAttributes.Private;
myClass_databaseAccessClasses.InitExpression = new CodeObjectCreateExpression(dictionaryType);
myClass.Members.Add(myClass_databaseAccessClasses);
CodeMemberProperty myClass_DatabaseAccessClasses = new CodeMemberProperty();
myClass_DatabaseAccessClasses.Name = "DatabaseAccessClasses";
myClass_DatabaseAccessClasses.Type = dictionaryType;
myClass_DatabaseAccessClasses.Attributes = MemberAttributes.Static | MemberAttributes.Private;
myClass_DatabaseAccessClasses.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(new CodeTypeReference("DataAccessFactory")), "databaseAccessClasses")));
myClass_DatabaseAccessClasses.SetStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(new CodeTypeReference("DataAccessFactory")), "databaseAccessClasses"), new CodeArgumentReferenceExpression("value")));
myClass.Members.Add(myClass_DatabaseAccessClasses);
StringWriter writer = new StringWriter();
codeProvider.GenerateCodeFromCompileUnit(compileUnit, writer, new System.CodeDom.Compiler.CodeGeneratorOptions());
」不是個這缺乏某種解釋?事實上,對於有類似問題但未完全相同的源代碼的未來訪問者來說,此答案不會非常有用。 – 2013-02-10 10:58:44