Sugerir tradução
 
Outras sugestões:

progress indicator
Sem sugestões.
Clique para classificar e enviar comentários
MSDN
Biblioteca MSDN
Visual Studio 2005
 Demonstra Passo a passo: Criando um...

  Ativar exibição de largura de banda baixa
Exibir Conteúdo: Lado a LadoExibir Conteúdo: Lado a Lado
Este conteúdo foi traduzido automaticamente e pode ser editado pelos membros da comunidade. Para melhorar a qualidade da tradução, clique no link Editar associado à frase que deseja modificar.
.NET Framework
Walkthrough: Authoring a Component with Visual C#

Components provide reusable code in the form of objects. An application that uses a component's code, by creating objects and calling their properties and methods, is referred to as a client. A client may or may not be in the same assembly as a component it uses.

The following procedures build on each other, so the order in which you perform them is important.

Note:

The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see Visual Studio Settings.

To create the CDemoLib class library and the CDemo component

  1. From the File menu, select New and then Project to open the New Project dialog. Select the Class Library project template from the list of Visual C# project types, and enter CDemoLib in the Name box.

    Note:

    Always specify the name of a new project when you create it. Doing so sets the root namespace, assembly name, and project name, and also ensures that the default component will be in the correct namespace.

  2. In Solution Explorer, right-click CDemoLib and select Properties from the shortcut menu. Notice that the Default namespace box contains CDemoLib.

    The root namespace is used to qualify the names of components in the assembly. For example, if two assemblies provide components named CDemo, you can specify your CDemo component using CDemoLib.CDemo.

    Close the dialog box.

  3. From the Project menu, choose Add Component.

  4. In the Add New Item dialog box, select Component Class and type CDemo.cs in the Name box. Click Add to crate the component.

    A component named CDemo is added to your class library.

  5. In Solution Explorer, right-click CDemo.cs and choose View Code from the shortcut menu. The code editor opens.

    Notice the : Component immediately after public partial class CDemo. This section designates the class from which your class inherits. By default, a component inherits from the Component class provided by the system. The Component class provides many features for your component, including the ability to use designers.

  6. In Solution Explorer, right-click Class1.cs and choose Delete. This deletes the default class that is provided with the class library, as it will not be used in this walkthrough.

  7. From the File menu, choose Save All to save the project.

Constructors control the way your component is initialized; the Finalize method controls the way it tears down. Code in the constructor and the Finalize method of the CDemo class maintains a running count of the number of CDemo objects in existence.

To add code for the constructor and destructor of the CDemo class

  1. In the Code Editor, add member variables to keep a running total of instances of the CDemo class, and an ID number for each instance.

    public readonly int InstanceID;
    private static int NextInstanceID = 0;
    private static long ClassInstanceCount = 0;

    Because the InstanceCount and NextInstanceID member variables are declared static, they exist only at the class level. All instances of CDemo that access these members will use the same memory locations. Static members will be initialized the first time the CDemo class is referred to in code. This could be the first time a CDemo object is created, or the first time one of the static members is accessed.

  2. Locate public CDemo() and public CDemo(IContainer container), the default constructors for the CDemo class. In Visual C#, all constructors have the same name as the class. Your component can have several constructors, with different parameters, but they must all have the same name as your component.

    Note:

    The access level of the constructors determines which clients will be able to create instances of the class.

  3. Add the following code to public CDemo(), to increment the instance count when a new CDemo is created, and to set the instance ID number.

    Note:

    Always add your code after the call to InitializeComponent. At that point, any constituent components have been initialized.

    InstanceID = NextInstanceID ++;
    ClassInstanceCount ++;

    As a readonly member, InstanceID can be set only in the constructor.

    Note:

    Users familiar with multithreading will point out quite rightly that assigning InstanceID and incrementing NextInstanceID should be an atomic operation. This and other issues related to threading are illustrated in Walkthrough: Authoring a Simple Multithreaded Component with Visual C#.

  4. Add the following method after the end of the constructor:

    ~CDemo()
    {
       ClassInstanceCount --;
    }

    This method is called a destructor, and is signified by the tilde character (~) in front of the class name. The memory manager calls the destructor just before it finally reclaims memory occupied by the CDemo object. By implementing a destructor you can perform cleanup just before your component is removed from memory. However, as you'll see later in this walkthrough, there are good reasons to release resources earlier.

The CDemo class has only one property, a static property that allows the client to find out how many CDemo objects there are in memory at any given time. Methods can be created in a similar way.

To create a property for the CDemo class

  • Add the following property declaration to the CDemo class, to allow clients to retrieve the number of instances of CDemo.

    public static long InstanceCount
       {
          get
          {
             return ClassInstanceCount;
          }
       }

To test the component, you need a project that uses it. This project must be the first project that starts when you press the Run button.

To add the CDemoTest client project as the startup project for the solution

  1. From the File menu, point to Add and choose New Project to open the Add New Project dialog box.

  2. Select the Windows Application project template, and type CDemoTest in the Name box and then click OK.

  3. In Solution Explorer, right-click CDemoTest and click Set as Startup Project from the shortcut menu.

In order to use the CDemo component, the client test project must have a reference to the class library project. After adding the reference, it is a good idea to add a using statement to the test application to simplify use of the component.

To add a reference to the class library project

  1. In Solution Explorer, right-click the References node immediately beneath CDemoTest, and select Add Reference from the shortcut menu.

  2. In the Add Reference dialog box, select the Projects tab.

  3. Double-click the CDemoLib class library project. CDemoLib will appear under the References node for the CDemoTest project.

  4. In Solution Explorer, right-click Form1.cs and select View Code from the shortcut menu.

Adding the reference to CDemoLib allows you to use the fully qualified name of the CDemo component — that is, CDemoLib.CDemo.

To add a using statement

  • Add the following using statement to the list of using statements at the top of the Code Editor for Form1.

    using CDemoLib;

    Adding the using statement allows you to omit the library name, and refer to the component type as CDemo.

    You will now create and use a test program to test your component.

The CDemoTest program will illustrate object lifetime in the .NET Framework by creating and releasing large numbers of CDemo objects.

To add code to create and release CDemo objects

  1. Click Form1.cs[Design] to return to the designer.

  2. Drag a Button and a Timer from the All Windows Forms tab of the Toolbox onto the Form1 design surface.

    The nonvisual Timer component appears on a separate design surface below the form.

  3. Double-click the icon for timer1 to create an event-handling method for the timer1 component's Tick event. Place the following code in the event-handling method.

    this.Text = "CDemo instances: " + CDemo.InstanceCount;

    On every tick of the timer, the form's caption will display the current instance count for the CDemo class. The class name is used as a qualifier for the static InstanceCount property — there is no need to create an instance of CDemo to access a static member.

  4. Locate the constructor for Form1 (public Form1()), and add the following code after the call to InitializeComponent().

    timer1.Enabled = true;

    This will start the timer as soon as the form is created.

  5. Click the Form1.cs [Design] tab to return to the designer.

  6. Double-click the Button on Form1, to create an event-handling method for the button's Click event. Place the following code in the event-handling method.

    CDemo cd;
    int ct;
    for (ct = 0; ct < 1000; ct++)
       cd = new CDemo();

    This code may look strange to you. As each instance of CDemo is created, the previous instance is released. When the for loop is done, there will be only one instance of CDemo left. When the event-handling method exits, even that instance will be released, because the variable cd will go out of scope.

    As you may have guessed already, things won't happen quite that way.

To run and debug the CDemoTest and CDemo projects

  1. Press F5 to start the solution.

    The client project will start, and Form1 will be displayed. Notice that the caption of the form displays "CDemo instances: 0".

  2. Click the button. The caption of the form should display "CDemo instances: 1000".

    The instances of CDemo were all released by the time the button's Click event-handling procedure finished. Why haven't they been finalized? In brief, the memory manager finalizes objects in the background, at low priority. The priority is only bumped up if the system gets low on memory. This lazy garbage collection scheme allows for very fast object allocation.

  3. Click the button several more times, watching the caption. At some point, the number of instances will suddenly drop. This means that the memory manager has reclaimed the memory of some of the objects.

    Note:

    If you've clicked more than 10 times, and the number of CDemo instances has not decreased, you may need to adjust the code so that it uses more memory. Close the form to return to the development environment, and increase the number of iterations in the for loop to 10000. Then run the project again.

  4. Repeat Step 3. You will get farther this time before the memory manager finalizes more objects.

    In fact, each time you repeat step 3, you will probably be able to allocate more CDemo objects before the memory manager steps in. This is because more and more of Visual Studio is swapped out, leaving more space for instances of CDemo.

  5. Close the form to return to the development environment.

.NET Framework
Demonstra Passo a passo: Criando um componente COM Visual C#

Componentes fornecem código reutilizável na forma de objetos. Um aplicativo que usa código de um componente, criando objetos e chamando seus métodos e propriedades, é conhecido como um cliente. Um cliente pode ou não estar no mesmo assembly que um componente que ele usa.

Os passos a seguir são incrementais, dependentes, então a ordem de execução é importante.

Observação:

As caixas de diálogo e comandos de menu demonstradas podem ser diferentes daqueles descritos na Ajuda, dependendo das configurações ativas ou configurações de edição. Para alterar estas configurações, escolha Importar e Exportar Configurações no menu de Ferramentas. Para obter mais informações, consulte Configurações do Visual Studio.

Para criar a biblioteca de classes CDemoLib e o componente CDemo

  1. From the menu File , Selecionar New and then Project to the diálogo New Project aberto. Selecionar The Class Library projeto modelo from the lista of types projeto Visual C# , and ENTER CDemoLib in the caixa Name.

    Observação:

    Sempre especificar o nome de um projeto novo quando você Criar-la. Doing Sets SO the raiz Namespace, assembly Name, and projeto Name, and also ensures that will be in the Correct the componente usar como padrão Namespace.

  2. In Gerenciador de Soluções, clique com o botão direito do mouse CDemoLib and Selecionar Properties from the menu atalho. Observe que o Namespace Padrão caixa contém CDemoLib.

    O namespace principal é usado para qualificar os nomes dos componentes no conjunto de módulos (assembly). Por exemplo, se dois conjuntos de módulos (assemblies) fornecer componentes chamados CDemo, você pode especificar o componente CDemoCDemoLib.CDemo usando.

    Close the Caixa de Diálogo.

  3. A partir de Projeto menu, escolher Adicionar Componente.

  4. Na caixa diálogo Add New Item, Selecionar Classe de componente e tipo CDemo.cs na caixa Nome. Clique em Adicionar para crate o componente.

    Um componente nomeado CDemo é adicionado à sua Biblioteca de Classes.

  5. In Gerenciador de Soluções, clique com o botão direito do mouse CDemo.cs and escolher View Código from the menu atalho. Abre o Editor de Código.

    Observe o : Component imediatamente após public partial class CDemo. Esta seção designa a classe da qual herda sua classe. Inherits a componente Por padrão, de the classe Component provided by the sistema. Provides the classe Component muitos Features For Your componente, including the ability to Use designers.

  6. In Solução Explorer, clique com o botão direito do mouse Class1.cs and escolher Delete. Isso exclui a classe padrão que é fornecida com a biblioteca de classes, como ele não irá ser usado nessa explicação passo a passo.

  7. No menu File, escolha Save All para salvar o projeto.

Construtores Controlar a maneira como seu componente é inicializado; o método Finalize Controles a maneira como ele tears para baixo. Código o construtor e a Finalize método de classe de CDemo mantém um contagem contínua do número de objetos CDemo na existência.

Para adicionar código para o construtor e destruidor da classe CDemo

  1. In the Editor de código, adicionar membro Variables to manter a execução total of instances of the classe CDemo, and an número identificação for each instância.

    public readonly int InstanceID;
    private static int NextInstanceID = 0;
    private static long ClassInstanceCount = 0;

    Porque o InstanceCount e NextInstanceID membro variáveis sejam declaradas static, existirem somente no nível de classe. Tudo instances of CDemo that acessar these members will Use the same Locations memória. Membros estáticos serão inicializados o tempo primeiro a classe CDemo é mencionado em Código. This Could be the first tempo is a objeto CDemo Criado, or the first tempo one of the members static is accessed.

  2. Localize public CDemo() e public CDemo(IContainer container), os construtores padrão para a classe CDemo. Em Visual C#, Tudo construtores têm o mesmo nome de classe. O componente pode ter vários construtores, com diferentes parâmetros, mas eles devem Tudo têm o mesmo nome como seu componente.

    Observação:

    O Acessar nível dos construtores determina quais os clientes poderão criar instâncias de classe.

  3. Add the seguinte Código to public CDemo(), to the contagem instância When a new CDemo is created incremento, and to Set the número identificação instância.

    Observação:

    Always adicionar Your Código after the chamar to InitializeComponent. Nesse ponto, quaisquer componentes constituintes foram inicializados.

    InstanceID = NextInstanceID ++;
    ClassInstanceCount ++;

    Como um membro readonly , InstanceID pode ser definida somente no construtor.

    Observação:

    Os usuários familiarizados com multithreading será bastante corretamente que atribuindo InstanceID e incrementar NextInstanceID devem ser uma operação atômica destaque. This and Outro Issues relacionado to segmento are illustrated in Passo-a-Passo: Criando um componente os Simples com Visual C#.

  4. Adicionar o seguinte método depois do fim do construtor:

    ~CDemo()
    {
       ClassInstanceCount --;
    }

    Este método é chamado um destruidor e é representado pelo caractere de til (~) na frente do nome de classe. The memória Gerente calls the destrutor just before it finally reclaims memória occupied by the objeto CDemo. Implementando um destruidor você pode executar a limpeza apenas antes que o componente seja removido de memória. However, as you 'll see later in this , there are reasons Good to versão Resources earlier.

A classe CDemo possui apenas uma propriedade, um Estático propriedade que permite que o cliente para localizar fora como muitos objetos CDemo existe correm qualquer tempo determinado na memória. Métodos podem ser criados de maneira semelhante.

Para criar uma propriedade para a classe CDemo

  • Adicionar The seguinte declaração propriedade to the classe CDemo , to Allow clients to the número of instances of CDemo recuperar.

    public static long InstanceCount
       {
          get
          {
             return ClassInstanceCount;
          }
       }

Para testar o componente, é necessário um projeto que usa-lo. This projeto must be the Primeiro projeto that Starts When You pressionar botão the Run.

Para adicionar o projeto do cliente CDemoTest como o projeto de inicialização para a solução

  1. No menu do arquivo, aponte para Adicionar e escolha Novo Projeto para abrir a caixa de diálogo Adicionar novo projeto.

  2. Selecionar The Windows Application projeto modelo, and tipo CDemoTest in the caixa Name and then clique OK.

  3. In Gerenciador de Soluções, clique com o botão direito do mouse CDemoTest and clique Set As Inicialização Project from the menu atalho.

In Ordem to use the componente CDemo, the projeto testar cliente must have a reference to the projeto de biblioteca de classes. Depois de adicionar a referência, ela é uma boa idéia para adicionar uma instrução using para o aplicativo de teste para simplificar Uso do componente.

Para adicionar uma referência para o Biblioteca de Classes projeto

  1. Em Gerenciador de Soluções, o nó referências imediatamente abaixo CDemoTest, clique com o botão direito do mouse e Selecionar Adicionar Referência do menu de atalho.

  2. Na caixa diálogo Add Reference, Selecionar na guia projetos.

  3. Duplo-clique the projeto de biblioteca de classes CDemoLib. CDemoLib aparecerá sob o nó referências para o projeto CDemoTest.

  4. In Gerenciador de Soluções, clique com o botão direito do mouse Form1.cs and SELECT View Código from the menu atalho.

Adicionar a referência CDemoLib permite que você use o nome totalmente qualificado do componente CDemo — isto é, CDemoLib.CDemo.

Para adicionar um usando instrução

  • Add the seguinte declaração using to the lista of Statements using at the parte superior of the Editor de código for Form1.

    using CDemoLib;

    Adicionando a instrução using permite que você omitir o nome da biblioteca e consulte o tipo de componente como CDemo.

    Agora você criará e usar um programa de teste para testar seu componente.

O programa CDemoTest irá ilustrar vida útil de objeto do .NET Framework, criando e liberando um grande número de objetos CDemo.

To codificar adicionar to create and Objects versão CDemo

  1. Clique em Form1.cs[Design] para retornar para o designer.

  2. Arraste um Button e um Timer na guia Tudo Windows Forms do A Caixa de ferramentas até as superfície de design Form1.

    O componente nonvisual Timer aparece em uma superfície de design separadas abaixo do formulário.

  3. Duplo-clique the ícone for timer1 to Create an evento-método manipulação for Tick evento the componente timer1 's. Place the Código in the - .

    this.Text = "CDemo instances: " + CDemo.InstanceCount;

    On every marcação of the timer, legenda 's the forma will exibir The atual instância Contar for the classe CDemo. Nome de classe é usado como um qualificador para a propriedade estático InstanceCount — existe é não precisa criar uma instância de CDemo para acessar um membro estático.

  4. Locate the construtor for Form1 (public Form1()), and adicionar the seguinte Código after the chamar to InitializeComponent().

    timer1.Enabled = true;

    Isso irá iniciar o timer assim o formulário é criado.

  5. Clique na guia Form1.cs [Design] para retornar para o designer.

  6. Duplo-clique o ButtonForm1, para criar um evento no-método manipulação para evento do botão Click. Place the Código in the - .

    CDemo cd;
    int ct;
    for (ct = 0; ct < 1000; ct++)
       cd = new CDemo();

    Esse código pode parecer estranho para você. As each of CDemo is Criado, the previous is released. When the executar um loop for is, there will be instância only one of CDemo Esquerda. When the evento-método manipulação exits, even that instância will be released, because the variável cd will go out of escopo.

    Como você pode ter tentativa já, não acontecem bastante dessa maneira.

Para executar e depurar o CDemoTest e CDemo projetos

  1. Pressionar F5 to the solução iniciar.

    The projeto cliente will Iniciar, and will be displayed Form1. Observe que exibe a legenda do formulário " instâncias CDemo: 0".

  2. Clique no botão. A legenda do formulário deve exibir " instâncias CDemo: 1000".

    Were the instances of CDemo Tudo released by the tempo evento Click 's the botão-procedimento manipulação Finished. Por que ainda não eles foi finalizados? In BRIEF, the Gerenciador memória finalizes Objetos in the segundo plano, at prioridade Low. A prioridade apenas é bumped backup se o sistema obtém Baixo na memória. Este esquema coleção de lixo lenta permite alocação Objeto muito rápido.

  3. Clique no botão Mais várias vezes, observando a legenda. At some apontar, the número of instances will suddenly Soltar. Isso significa que a memória Gerente tem recuperou a memória de alguns dos objetos.

    Observação:

    If you 've clicked more than times 10, and the número of instances CDemo not has decreased, you May need to Adjust the Código so that it uses memória more. Feche o Formulário para retornar para o ambiente de desenvolvimento e aumentar o número de iterações na executar um loop for para 10000. Em seguida, executar o projeto novamente.

  4. Repetir Etapa 3. Você irá get afaste esse tempo antes de memória Gerente finaliza mais objetos.

    Na verdade, cada tempo você repetir etapa 3, você provavelmente poderá alocar mais objetos CDemo antes de memória Gerente as etapas no. Isso ocorre porque mais e mais Visual Studio é trocado check-out, deixando mais espaço para instâncias de CDemo.

  5. Close the Formulário to Return to the ambiente de desenvolvimento.

Conteúdo da Comunidade   O que é Conteúdo da Comunidade?
Adicionar novo conteúdo RSS  Anotações
Processing
© 2009 Microsoft Corporation. Todos os direitos reservados. Termos de Uso  |  Marcas Comerciais  |  Política de Privacidade
Page view tracker