//将DesignerHost中的Component转成CodeType private CodeTypeDeclaration ConvertComponentToCodeType() { //componentInDesign = this.LoadComponent(componentInDesign); DesignerSerializationManager manager = new DesignerSerializationManager(this._serviceProvider); //这句Code是必须的,必须要有一个session,DesignerSerializationManager才能工作 IDisposable session = manager.CreateSession(); TypeCodeDomSerializer serializer = manager.GetSerializer(componentInDesign.GetType(), typeof(TypeCodeDomSerializer)) as TypeCodeDomSerializer; List <object> list = new List <object>(); foreach (IComponent item in this.DesignerHost.Container.Components) { //PropertyInfo vName = item.GetType().GetProperty("Name"); //if (vName != null) //{ // string realName = vName.GetValue(item) as string; // if (realName == "") // { // vName.SetValue(item, "RENAMED"); // } //} list.Add(item); } CodeTypeDeclaration declaration = serializer.Serialize(manager, componentInDesign, list); session.Dispose(); return(declaration); }