- Visual Studio C#: Partial Class in Windows Form(Разделяемые классы)
- Partial Form Class C# — Only display code view for class
- 1 Answer 1
- Использование Partial для класса формы
- 3 ответа 3
- Всё ещё ищете ответ? Посмотрите другие вопросы с метками c# visual-studio winforms или задайте свой вопрос.
- Связанные
- Похожие
- Подписаться на ленту
- Partial Classes and Methods (C# Programming Guide)
- Partial Classes
- Restrictions
- Example 1
- Description
- Example 2
- Description
- Partial Methods
- C# Language Specification
- Разделяемые классы и методы (Руководство по программированию в C#) Partial Classes and Methods (C# Programming Guide)
- Разделяемые классы Partial Classes
- Ограничения Restrictions
- Пример 1 Example 1
- Описание Description
- Код Code
- Пример 2 Example 2
- Описание Description
- Код Code
- Разделяемые методы Partial Methods
- Спецификация языка C# C# Language Specification
Visual Studio C#: Partial Class in Windows Form(Разделяемые классы)
Недавно столкнулся с такой задачкой.
В основной форме программы (в файле MainForm.cs) сформировалось достаточно большое количество кода. Я решил, что было бы неплохо, разделить по файлам код относящейся непосредственно к самой форме, например методы обработки кнопок, меню и т.д. и сам исполнительный код, используя возможности разделяемых классов — Partial Class .
Для решения этой задачи в обозревателе решений Visual Studio необходимо создать файл MainForm.implementation.cs. Результат создания представлен на скриншоте ниже.
В данный момент файл MainForm.implementation.cs ни логически, ни физически не имеет отношения к форме MainForm.
При этом файл был создан и размещен в той же папке, что остальные файлы.
Для логического отображения файла в составе формы, необходимо перейти к Visual C# Project file (с расширением .csproj). Файл решения и файл проекта обычно расположены в корневой папке.
Файл FilmCollection.csproj необходимо открыть в любом текстовом редакторе типа блокнот или Notepad++.
Затем необходимо найти следующую строку:
и заменить ее на строку:
Далее можно запустить решение в Visual Studio и увидим, что нужный файл теперь является вложенным к форме MainForm. Скришот ниже.
В завершение открываем добавленный файл MainForm.implementation.cs и добавляем в него строки по аналогии с файлом MainForm.Designer.cs
Ключевое слово partial необходимо для обозначения кода текущего файла как часть класса MainForm, это и есть проявление разделяемых классов (Partial Class).
Partial Form Class C# — Only display code view for class
I have a Blank Forms project in C#.
I wanted to separate the functions and events into different Codefiles on the Form Class. In order to make it more manageable when it becomes large and multiple people are using it on CodeControl.
These extra partial classes both consist of
I also changed the csproj file so the VS IDE would make them appear in the Soution Explorer.
So the program compiles and all is looking good except that when I open the file from the solution explorer it opens up a blank Form designer, and not the code.
I want VS to only open this class as a code file to limit issues with the Form1.Designer.cs file.
I have also tried removing the SubType
but Visual Studio keeps adding it back to the csproj file.
1 Answer 1
As mentioned on the comments, Visual Studio will open any file ending with .Designer.cs in the code editor rather than on the forms designer. Taking advantage of this, a good solution to have a form not open in the form designer is to name the file that contains the class with ending .Designer.cs .
Note: I would say this is not elegant. I find it counter intuitive to have a file named Form1.Designer.cs and don’t have a designer for it. Also, if the form was originally created with the forms designer, this will require to merge Form1.cs and Form1.Designer.cs which can be problematic from within Visual Studio.
My original answer
Follow these steps:
1) Make sure the designer is closed.
2) Modify your Form1.Designer.cs and add the attribute DesignerCategory with the empty string «» (any random value other than «Designer», «Form» or «Component» also works — case insensitive):
3) Unload your project.
4) Reload your project.
5) Notice the designer doesn’t appear.
Note: tested on Visual Studio 2012, yet based on a discussion thread from 2005.
Использование Partial для класса формы
Пытаюсь разделять код на файлы. Вот заголовок моего класса:
Во втором файле пишу:
Всё работает, но в Solution Explorer этот файл отображается как форма (наверняка потому что подключена Windows.Forms). Я то хотел только код а тут такое, это нормально?
3 ответа 3
Да, это нормально: ведь всё это один и тот же класс.
Я рекомендую обратить внимание вот на что.
Если кода стало много и начинаете делить класс на несколько листингов через partial — то давно пора задумываться о рефакторинге и вынесении части бизнес-логики в отдельные классы.
И уже для новых классов выбирайте при вставке тип Class , а не Windows Form :
Да, можно сделать правильное отображение вашего дополнительного файла как файла с кодом.
После создания данного файла (я назвал его Form1Ext.cs) выполните построение проекта.
Выгрузите проект: правый клик мышкой на проекте в Solution Explorer > Unload Project.
Откройте любым текстовым редактором (можно Блокнотом) файл
Конечно, ищите название своего файла.
Замените вложенный узел
Сохраните файл *.csproj. Можно закрыть текстовый редактор.
Загрузите проект: ПКМ на проекте > Reload Project.
У меня получилось следующее отображение в Solution Explorer:
А я бы сказал что не стоит класс формы делить на части. Основная причина — это визуальный редактор. По своему (многолетнему) опыту могу сказать — Visual Studio плохо переваривает такие вещи как разделение формы на части, и наследование тоже. То что у вас в Solution Explorer показывается не так как хочется — это ещё цветочки. А вот когда вы не сможете (совсем) открыть редактор — тогда всё, править только руками, что сильно повлияет на вашу производительность.
- Не использовать наследование на формах, не делить на partial классы
- Выделяйте функциональность относящуюся к вычислениям, доступу к данным в отдельные классы
- Выделяйте однотипные визуальные блоки в отдельные User Controls
Всё ещё ищете ответ? Посмотрите другие вопросы с метками c# visual-studio winforms или задайте свой вопрос.
Связанные
Похожие
Подписаться на ленту
Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.
дизайн сайта / логотип © 2021 Stack Exchange Inc; материалы пользователей предоставляются на условиях лицензии cc by-sa. rev 2021.4.16.39093
Partial Classes and Methods (C# Programming Guide)
It is possible to split the definition of a class, a struct, an interface or a method over two or more source files. Each source file contains a section of the type or method definition, and all parts are combined when the application is compiled.
Partial Classes
There are several situations when splitting a class definition is desirable:
When working on large projects, spreading a class over separate files enables multiple programmers to work on it at the same time.
When working with automatically generated source, code can be added to the class without having to recreate the source file. Visual Studio uses this approach when it creates Windows Forms, Web service wrapper code, and so on. You can create code that uses these classes without having to modify the file created by Visual Studio.
To split a class definition, use the partial keyword modifier, as shown here:
The partial keyword indicates that other parts of the class, struct, or interface can be defined in the namespace. All the parts must use the partial keyword. All the parts must be available at compile time to form the final type. All the parts must have the same accessibility, such as public , private , and so on.
If any part is declared abstract, then the whole type is considered abstract. If any part is declared sealed, then the whole type is considered sealed. If any part declares a base type, then the whole type inherits that class.
All the parts that specify a base class must agree, but parts that omit a base class still inherit the base type. Parts can specify different base interfaces, and the final type implements all the interfaces listed by all the partial declarations. Any class, struct, or interface members declared in a partial definition are available to all the other parts. The final type is the combination of all the parts at compile time.
The partial modifier is not available on delegate or enumeration declarations.
The following example shows that nested types can be partial, even if the type they are nested within is not partial itself.
At compile time, attributes of partial-type definitions are merged. For example, consider the following declarations:
They are equivalent to the following declarations:
The following are merged from all the partial-type definitions:
generic-type parameter attributes
For example, consider the following declarations:
They are equivalent to the following declarations:
Restrictions
There are several rules to follow when you are working with partial class definitions:
All partial-type definitions meant to be parts of the same type must be modified with partial . For example, the following class declarations generate an error:
The partial modifier can only appear immediately before the keywords class , struct , or interface .
Nested partial types are allowed in partial-type definitions as illustrated in the following example:
All partial-type definitions meant to be parts of the same type must be defined in the same assembly and the same module (.exe or .dll file). Partial definitions cannot span multiple modules.
The class name and generic-type parameters must match on all partial-type definitions. Generic types can be partial. Each partial declaration must use the same parameter names in the same order.
The following keywords on a partial-type definition are optional, but if present on one partial-type definition, cannot conflict with the keywords specified on another partial definition for the same type:
new modifier (nested parts)
Example 1
Description
In the following example, the fields and the constructor of the class, Coords , are declared in one partial class definition, and the member, PrintCoords , is declared in another partial class definition.
Example 2
Description
The following example shows that you can also develop partial structs and interfaces.
Partial Methods
A partial class or struct may contain a partial method. One part of the class contains the signature of the method. An implementation can be defined in the same part or another part. If the implementation is not supplied, then the method and all calls to the method are removed at compile time. Implementation may be required depending on method signature.
Partial methods enable the implementer of one part of a class to define a method, similar to an event. The implementer of the other part of the class can decide whether to implement the method or not. If the method is not implemented, then the compiler removes the method signature and all calls to the method. The calls to the method, including any results that would occur from evaluation of arguments in the calls, have no effect at run time. Therefore, any code in the partial class can freely use a partial method, even if the implementation is not supplied. No compile-time or run-time errors will result if the method is called but not implemented.
Partial methods are especially useful as a way to customize generated code. They allow for a method name and signature to be reserved, so that generated code can call the method but the developer can decide whether to implement the method. Much like partial classes, partial methods enable code created by a code generator and code created by a human developer to work together without run-time costs.
A partial method declaration consists of two parts: the definition, and the implementation. These may be in separate parts of a partial class, or in the same part. If there is no implementation declaration, then the compiler optimizes away both the defining declaration and all calls to the method.
Partial method declarations must begin with the contextual keyword partial.
Partial method signatures in both parts of the partial type must match.
Partial methods can have static and unsafe modifiers.
Partial methods can be generic. Constraints are put on the defining partial method declaration, and may optionally be repeated on the implementing one. Parameter and type parameter names do not have to be the same in the implementing declaration as in the defining one.
You can make a delegate to a partial method that has been defined and implemented, but not to a partial method that has only been defined.
A partial method isn’t required to have an implementation in the following cases:
It doesn’t have any accessibility modifiers (including the default private).
It doesn’t have any out parameters.
It doesn’t have any of the following modifiers virtual, override, sealed, new, or extern.
Any method that doesn’t conform to all those restrictions (for example, public virtual partial void method), must provide an implementation.
C# Language Specification
For more information, see Partial types in the C# Language Specification. The language specification is the definitive source for C# syntax and usage.
Разделяемые классы и методы (Руководство по программированию в C#) Partial Classes and Methods (C# Programming Guide)
Можно разделить определение класса, структуры, интерфейса или метода между двумя или более исходными файлами. It is possible to split the definition of a class, a struct, an interface or a method over two or more source files. Каждый исходный файл содержит часть определения класса или метода, а во время компиляции приложения все части объединяются. Each source file contains a section of the type or method definition, and all parts are combined when the application is compiled.
Разделяемые классы Partial Classes
Существует несколько ситуаций, когда желательно разделение определения класса. There are several situations when splitting a class definition is desirable:
При работе над большими проектами распределение класса между различными файлами позволяет нескольким программистам работать с ним одновременно. When working on large projects, spreading a class over separate files enables multiple programmers to work on it at the same time.
При работе с использованием автоматически создаваемого источника код можно добавлять в класс без повторного создания файла источника. When working with automatically generated source, code can be added to the class without having to recreate the source file. Visual Studio использует этот подход при создании форм Windows Forms, кода оболочки веб-службы и т. д. Visual Studio uses this approach when it creates Windows Forms, Web service wrapper code, and so on. Можно создать код, который использует эти классы, без необходимости изменения файла, созданного в Visual Studio. You can create code that uses these classes without having to modify the file created by Visual Studio.
Чтобы разделить определение класса, используйте модификатор ключевого слова partial, как показано ниже: To split a class definition, use the partial keyword modifier, as shown here:
Ключевое слово partial указывает, что другие части класса, структуры или интерфейса могут быть определены в пространстве имен. The partial keyword indicates that other parts of the class, struct, or interface can be defined in the namespace. Все части должны использовать ключевое слово partial . All the parts must use the partial keyword. Для формирования окончательного типа все части должны быть доступны во время компиляции. All the parts must be available at compile time to form the final type. Все части должны иметь одинаковые модификаторы доступа, например public , private и т. д. All the parts must have the same accessibility, such as public , private , and so on.
Если какая-либо из частей объявлена абстрактной, то весь тип будет считаться абстрактным. If any part is declared abstract, then the whole type is considered abstract. Если какая-либо из частей объявлена запечатанной, то весь тип будет считаться запечатанным. If any part is declared sealed, then the whole type is considered sealed. Если какая-либо из частей объявляет базовый тип, то весь тип будет наследовать данный класс. If any part declares a base type, then the whole type inherits that class.
Все части, указывающие базовый класс, должны быть согласованы друг с другом, а части, не использующие базовый класс, все равно наследуют базовый тип. All the parts that specify a base class must agree, but parts that omit a base class still inherit the base type. Части могут указывать различные базовые интерфейсы, и окончательный тип будет реализовывать все интерфейсы, перечисленные во всех разделяемых объявлениях. Parts can specify different base interfaces, and the final type implements all the interfaces listed by all the partial declarations. Любые члены класса, структуры или интерфейса, объявленные в разделяемом объявлении, доступны для всех остальных частей. Any class, struct, or interface members declared in a partial definition are available to all the other parts. Окончательный тип представляет собой комбинацию всех частей, выполненную во время компиляции. The final type is the combination of all the parts at compile time.
Модификатор partial недоступен в объявлениях делегатов или перечислений. The partial modifier is not available on delegate or enumeration declarations.
В следующем примере показано, что вложенные типы могут быть разделяемыми, даже если тип, в который они вложены, не является разделяемым. The following example shows that nested types can be partial, even if the type they are nested within is not partial itself.
Во время компиляции атрибуты определений разделяемого типа объединяются. At compile time, attributes of partial-type definitions are merged. В качестве примера рассмотрим следующие объявления: For example, consider the following declarations:
Они эквивалентны следующим объявлениям: They are equivalent to the following declarations:
Следующие элементы объединяются из всех определений разделяемого типа: The following are merged from all the partial-type definitions:
XML-комментарии XML comments
атрибуты параметров универсального параметра generic-type parameter attributes
атрибуты классов class attributes
В качестве примера рассмотрим следующие объявления: For example, consider the following declarations:
Они эквивалентны следующим объявлениям: They are equivalent to the following declarations:
Ограничения Restrictions
Имеется несколько правил, которые необходимо выполнять при работе с определениями разделяемого класса. There are several rules to follow when you are working with partial class definitions:
Все определения разделяемого типа, являющиеся частями одного типа, должны изменяться с использованием типа partial . All partial-type definitions meant to be parts of the same type must be modified with partial . Например, следующие объявления класса приведут к появлению ошибки: For example, the following class declarations generate an error:
Модификатор partial должен находиться непосредственно перед ключевыми словами class , struct или interface . The partial modifier can only appear immediately before the keywords class , struct , or interface .
В определениях разделяемого типа могут присутствовать вложенные разделяемые типы, что показано в следующем примере: Nested partial types are allowed in partial-type definitions as illustrated in the following example:
Все определения разделяемого типа, являющиеся частями одного и того же типа, должны быть определены в одной сборке и в одном модуле (EXE-файл или DLL-файл). All partial-type definitions meant to be parts of the same type must be defined in the same assembly and the same module (.exe or .dll file). Разделяемые определения не могут находиться в разных модулях. Partial definitions cannot span multiple modules.
Имя класса и параметры универсального типа должны соответствовать всем определениям разделяемого типа. The class name and generic-type parameters must match on all partial-type definitions. Универсальные типы могут быть разделяемыми. Generic types can be partial. Все объявления разделяемого типа должны использовать одинаковые имена параметров в одном и том же порядке. Each partial declaration must use the same parameter names in the same order.
Приведенные ниже ключевые слова необязательно должны присутствовать в определении разделяемого типа, но если они присутствуют в одном определении разделяемого типа, то не должны конфликтовать с ключевыми словами, указанными в других определениях того же разделяемого типа. The following keywords on a partial-type definition are optional, but if present on one partial-type definition, cannot conflict with the keywords specified on another partial definition for the same type:
базовый класс base class
модификатор new (вложенные части) new modifier (nested parts)
универсальные ограничения generic constraints
Дополнительные сведения см. в разделе Ограничения параметров типа. For more information, see Constraints on Type Parameters.
Пример 1 Example 1
Описание Description
В следующем примере поля и конструктор класса Coords объявлены в одном определении разделяемого класса, а член PrintCoords — в другом определении разделяемого класса. In the following example, the fields and the constructor of the class, Coords , are declared in one partial class definition, and the member, PrintCoords , is declared in another partial class definition.
Код Code
Пример 2 Example 2
Описание Description
В следующем примере показано, что можно также разработать разделяемые структуры и интерфейсы. The following example shows that you can also develop partial structs and interfaces.
Код Code
Разделяемые методы Partial Methods
Разделяемый класс или структура могут содержать разделяемый метод. A partial class or struct may contain a partial method. Одна часть класса содержит сигнатуру метода. One part of the class contains the signature of the method. В той же или в другой части можно определить реализацию. An implementation can be defined in the same part or another part. Если реализация не предоставлена, метод и все вызовы метода удаляются во время компиляции. If the implementation is not supplied, then the method and all calls to the method are removed at compile time. Реализация может потребоваться в зависимости от сигнатуры метода. Implementation may be required depending on method signature.
Разделяемые методы позволяют разработчику одной части класса определить метод, схожий с событием. Partial methods enable the implementer of one part of a class to define a method, similar to an event. Разработчик другой части класса может решить, реализовывать этот метод или нет. The implementer of the other part of the class can decide whether to implement the method or not. Если метод не реализован, то компилятор удаляет сигнатуру метода и все вызовы этого метода. If the method is not implemented, then the compiler removes the method signature and all calls to the method. Вызовы метода, включая любые результаты, которые могли бы произойти от оценки аргументов в вызовах, не имеют эффекта во время выполнения. The calls to the method, including any results that would occur from evaluation of arguments in the calls, have no effect at run time. Таким образом, любой код в разделяемом классе может свободно использовать разделяемый метод, даже если реализация не предоставлена. Therefore, any code in the partial class can freely use a partial method, even if the implementation is not supplied. Во время компиляции и выполнения программы не возникнут никакие ошибки, если метод будет вызван, но не реализован. No compile-time or run-time errors will result if the method is called but not implemented.
Разделяемые методы особенно полезны для настройки автоматически созданного кода. Partial methods are especially useful as a way to customize generated code. Они позволяют зарезервировать имя и сигнатуру метода, чтобы автоматически созданный код мог вызвать метод, а разработчик мог сам решить, реализовывать этот метод или нет. They allow for a method name and signature to be reserved, so that generated code can call the method but the developer can decide whether to implement the method. Как и разделяемые классы, разделяемые методы позволяют организовать совместную работу автоматически созданного кода и кода, созданного человеком, без дополнительных затрат во время выполнения. Much like partial classes, partial methods enable code created by a code generator and code created by a human developer to work together without run-time costs.
Объявление разделяемого метода состоит из двух частей: определения и реализации. A partial method declaration consists of two parts: the definition, and the implementation. Они могут находиться в разных частях или в одной и той же части разделяемого класса. These may be in separate parts of a partial class, or in the same part. Если объявление реализации отсутствует, то компилятор оптимизирует код, удаляя как объявление определения, так и все вызовы метода. If there is no implementation declaration, then the compiler optimizes away both the defining declaration and all calls to the method.
Объявления разделяемого метода должны начинаться с контекстного ключевого слова partial. Partial method declarations must begin with the contextual keyword partial.
Сигнатуры разделяемого метода в обеих частях разделяемого типа должны совпадать. Partial method signatures in both parts of the partial type must match.
Разделяемые методы могут иметь модификаторы static и unsafe. Partial methods can have static and unsafe modifiers.
Разделяемые методы могут быть универсальными. Partial methods can be generic. Ограничения налагаются на ту часть объявления разделяемого метода, где находится определение, и могут дополнительно повторяться в разделе реализации. Constraints are put on the defining partial method declaration, and may optionally be repeated on the implementing one. Имена параметров и типов параметров необязательно должны совпадать в объявлении реализации и в объявлении определения. Parameter and type parameter names do not have to be the same in the implementing declaration as in the defining one.
Можно использовать делегат в качестве определенного и реализованного разделяемого метода, но его нельзя использовать в качестве разделяемого метода, который только определен. You can make a delegate to a partial method that has been defined and implemented, but not to a partial method that has only been defined.
Разделяемый метод может не иметь реализацию в следующих случаях. A partial method isn’t required to have an implementation in the following cases:
У него нет модификаторов доступа (включая private по умолчанию). It doesn’t have any accessibility modifiers (including the default private).
Он возвращает значение void. It returns void.
У него нет параметров out. It doesn’t have any out parameters.
У него нет ни одного из следующих модификаторов: virtual, override, sealed, new или extern. It doesn’t have any of the following modifiers virtual, override, sealed, new, or extern.
Любой метод, не соответствующий всем этим ограничениям (например, метод public virtual partial void ), должен предоставлять реализацию. Any method that doesn’t conform to all those restrictions (for example, public virtual partial void method), must provide an implementation.
Спецификация языка C# C# Language Specification
Дополнительные сведения см. в разделе Разделяемые типы в Спецификации языка C#. For more information, see Partial types in the C# Language Specification. Спецификация языка является предписывающим источником информации о синтаксисе и использовании языка C#. The language specification is the definitive source for C# syntax and usage.