Compartilhar via


Não ignorar resultados do método

TypeName

DoNotIgnoreMethodResults

CheckId

CA1806

Category (Categoria)

Microsoft.uso

Quebrando alterar

Não separável

Causa

Um novo objeto é criado mas nunca usado.

- ou -

Um método que cria e retorna uma nova seqüência de caracteres é chamado e a nova seqüência nunca é usada.

- ou -

Um método COM ou P/Invoke, que retorna um código de erro de HRESULT ou que nunca é usado.

Descrição da regra

Esta regra ajuda conscientizá-lo das circunstâncias, sistema autônomo a seguir quando aparecem no seu código:

  • Criação do objeto desnecessário e a coleta de lixo associado do objeto não utilizado degradar o desempenho.

  • As seqüências de caracteres são imutáveis.Métodos, sistema autônomo ToUpper retorne uma nova instância de uma seqüência de caracteres em vez de modificar a instância de seqüência de caracteres do método de chamada.

  • Ignorar um código de erro ou HRESULT pode levar para um comportamento inesperado em condições de erro ou condições de recursos de baixo.

Como corrigir violações

Se um método cria uma nova instância do objeto B que nunca é usado, passe a instância sistema autônomo um argumento para outro método ou atribuir a instância de uma variável.Se a criação de objeto é desnecessária, remova-o.

- ou -

Um método chama o método B, mas não usa a nova instância de seqüência de caracteres que método B retorna.Passe a instância sistema autônomo um argumento para outro método, atribua a instância a uma variável ou remover a telefonar se for desnecessário.

- ou -

Um método chama o método B, mas não usa o código de erro de HRESULT ou que o método retorna.Usar o resultado em uma demonstrativo condicional, o resultado de atribuir a uma variável ou passe-lo sistema autônomo um argumento para outro método.

Quando suprimir avisos

Elimina um aviso da regra, a menos que o ato de criar o objeto tem algumas finalidade.

Exemplo

O exemplo a seguir mostra uma classe que ignora o resultado da chamada Trim.

Imports System

Namespace Samples

    Public Class Book

        Private ReadOnly _Title As String

        Public Sub New(ByVal title As String)

            If title IsNot Nothing Then
                ' Violates this rule                
                title.Trim()
            End If

            _Title = title

        End Sub

        Public ReadOnly Property Title() As String
            Get
                Return _Title
            End Get
        End Property

    End Class

End Namespace
using System;

namespace Samples
{
    public class Book
    {
        private readonly string _Title;

        public Book(string title)
        {
            if (title != null)
            {
                // Violates this rule                
                title.Trim();
            }

            _Title = title;
        }

        public string Title
        {
            get { return _Title; }
        }
    }
}
using namespace System;

namespace Samples
{
    public ref class Book   
    { 
        private:        
            initonly String^ _Title;

        public:
        Book(String^ title)        
        {               
            if (title != nullptr)            
            {                  
                // Violates this rule                
                title->Trim();            
            }
                _Title = title;        
            }

        property String^ Title        
        {            
            String^ get() { return _Title; }        
        }    
    };
}

O exemplo a seguir corrige a violação anterior, atribuindo o resultado de Trim volta para a variável foi chamada em.

Imports System

Namespace Samples

    Public Class Book

        Private ReadOnly _Title As String

        Public Sub New(ByVal title As String)

            If title IsNot Nothing Then
                title = title.Trim()
            End If

            _Title = title

        End Sub

        Public ReadOnly Property Title() As String
            Get
                Return _Title
            End Get
        End Property

    End Class

End Namespace
using System;

namespace Samples
{
    public class Book
    {
        private readonly string _Title;

        public Book(string title)
        {
            if (title != null)
            {
                title = title.Trim();
            }

            _Title = title;
        }

        public string Title
        {
            get { return _Title; }
        }
    }
}
using namespace System;

namespace Samples
{    
    public ref class Book    
    {    
    private:        
        initonly String^ _Title;

    public:
        Book(String^ title)        
        {               
            if (title != nullptr)            
            {                        
                title = title->Trim();            
            }

            _Title = title;        
        }

        property String^ Title        
        {            
            String^ get() { return _Title; }        
        }    
    };
}

O exemplo a seguir mostra um método que não usa um objeto que ele cria.

Observação:

Essa violação não pode ser reproduzida no Visual Basic.

using System;

namespace Samples
{
    public class Book
    {
        public Book()
        {
        }

        public static Book CreateBook()
        {
            // Violates this rule            
            new Book();
            return new Book();
        }
    }
}
using namespace System;

namespace Samples
{    
    public ref class Book    
    {
    public:
        Book()        
        {        
        }

        static Book^ CreateBook()        
        {
            // Violates this rule            
            gcnew Book();            
            return gcnew Book();        
        }    
    };
}

O exemplo a seguir corrige a violação anterior, removendo a criação de um objeto desnecessária.

using System;

namespace Samples
{
    public class Book
    {
        public Book()
        {
        }

        public static Book CreateBook()
        {
            return new Book();
        }
    }
}
using namespace System;

namespace Samples
{
    public ref class Book    
    {
    public:
        Book()        
        {           
        }
        static Book^ CreateBook()        
        {            
            return gcnew Book();        
        }            
    };
}

O exemplo a seguir mostra um método que ignora o erro de código que o método nativo GetShortPathName retorna.

Imports System
Imports System.ComponentModel
Imports System.IO
Imports System.Runtime.InteropServices
Imports System.Text

Namespace Samples

    Public Module FileIO

        Public Function GetShortPath(ByVal longPath As String) As String

            longPath = Path.GetFullPath(longPath)

            Const MAX_PATH As Integer = 260

            Dim shortPathBuffer As New StringBuilder(MAX_PATH)

            ' Violates this rule
            NativeMethods.GetShortPathName(longPath, shortPathBuffer, shortPathBuffer.Capacity)

            Return shortPathBuffer.ToString()

        End Function

    End Module

    Friend Module NativeMethods

        <DllImport("kernel32.dll", CharSet:=CharSet.Auto, SetLastError:=True, BestFitMapping:=False, ThrowOnUnmappableChar:=True)> _
        Public Function GetShortPathName(ByVal lpszLongPath As String, ByVal lpszShortPath As StringBuilder, ByVal cchBuffer As UInteger) As UInteger
        End Function

    End Module

End Namespace

using System;
using System.ComponentModel;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;

namespace Samples
{
    public static class FileIO
    {
        public static string GetShortPath(string longPath)
        {
            longPath = Path.GetFullPath(longPath);

            const int MAX_PATH = 260;

            StringBuilder shortPathBuffer = new StringBuilder(MAX_PATH);

            // Violates this rule
            NativeMethods.GetShortPathName(longPath, shortPathBuffer, (uint)shortPathBuffer.Capacity);

            return shortPathBuffer.ToString();
        }
    }

    internal static class NativeMethods
    {
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false, ThrowOnUnmappableChar = true)]
        public static extern uint GetShortPathName(string lpszLongPath, StringBuilder lpszShortPath, uint cchBuffer);
    }
}
#include "stdafx.h"

using namespace System;
using namespace System::ComponentModel;
using namespace System::IO;
using namespace System::Runtime::InteropServices;
using namespace System::Text;

namespace Samples
{
    private ref class NativeMethods sealed
    {
    private:
        NativeMethods()
        {
        }

    internal:

        [DllImport("kernel32.dll", CharSet=CharSet::Auto, SetLastError=true, BestFitMapping=false, ThrowOnUnmappableChar=true)]
        static unsigned int GetShortPathName(String^ lpszLongPath, StringBuilder^ lpszShortPath, unsigned int cchBuffer);
    };
    
    public ref class FileIO sealed
    {
    private:
        FileIO()
        {
        }

    public:
        static String^ GetShortPath(String^ longPath)
        {
            longPath = Path::GetFullPath(longPath);

            const int MAX_PATH = 260;

            StringBuilder^ shortPathBuffer = gcnew StringBuilder(MAX_PATH);

            // Violates this rule
            NativeMethods::GetShortPathName(longPath, shortPathBuffer, shortPathBuffer->Capacity);

            return shortPathBuffer->ToString();
        }
    };
}

O exemplo a seguir corrige a violação anterior ao verificar o código de erro e gerar uma exceção quando a telefonar falhar.

Namespace Samples

    Public Module FileIO_1

        Public Function GetShortPath(ByVal longPath As String) As String

            longPath = Path.GetFullPath(longPath)

            Const MAX_PATH As Integer = 260

            Dim shortPathBuffer As New StringBuilder(MAX_PATH)

            ' GetShortPathName returns 0 when the operation fails
            If NativeMethods.GetShortPathName(longPath, shortPathBuffer, shortPathBuffer.Capacity) = 0 Then

                ' Note: The constructor of Win32Exception will automatically
                ' set Win32Exception.NativeErrorCode to Marshal.GetLastWin32Error()
                Throw New Win32Exception()

            End If

            Return shortPathBuffer.ToString()

        End Function

    End Module

    Friend Module NativeMethods_1

        <DllImport("kernel32.dll", CharSet:=CharSet.Auto, SetLastError:=True, BestFitMapping:=False, ThrowOnUnmappableChar:=True)> _
        Public Function GetShortPathName(ByVal lpszLongPath As String, ByVal lpszShortPath As StringBuilder, ByVal cchBuffer As UInteger) As UInteger
        End Function

    End Module

End Namespace
namespace Samples
{
    public static class FileIO_1
    {
        public static string GetShortPath(string longPath)
        {
            const int MAX_PATH = 260;

            StringBuilder shortPathBuffer = new StringBuilder(MAX_PATH);

            // GetShortPathName returns 0 when the operation fails
            if (NativeMethods.GetShortPathName(longPath, shortPathBuffer, (uint)shortPathBuffer.Capacity) == 0)
            {
                // Note: The constructor of Win32Exception will automatically
                // set Win32Exception.NativeErrorCode to Marshal.GetLastWin32Error()
                throw new Win32Exception();
            }

            return shortPathBuffer.ToString();
        }
    }

    internal static class NativeMethods_1
    {
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false, ThrowOnUnmappableChar = true)]
        public static extern uint GetShortPathName(string lpszLongPath, StringBuilder lpszShortPath, uint cchBuffer);
    }
}
#include "stdafx.h"

using namespace System;
using namespace System::ComponentModel;
using namespace System::IO;
using namespace System::Runtime::InteropServices;
using namespace System::Text;

namespace Samples
{
    private ref class NativeMethods_1 sealed
    {
    private:
        void NativeMethods()
        {
        }

    internal:

        [DllImport("kernel32.dll", CharSet=CharSet::Auto, SetLastError=true, BestFitMapping=false, ThrowOnUnmappableChar=true)]
        static unsigned int GetShortPathName(String^ lpszLongPath, StringBuilder^ lpszShortPath, unsigned int cchBuffer);
    };
    
    public ref class FileIO_1 sealed
    {
    private:
        void FileIO()
        {
        }

    public:
        static String^ GetShortPath(String^ longPath)
        {
            longPath = Path::GetFullPath(longPath);

            const int MAX_PATH = 260;

            StringBuilder^ shortPathBuffer = gcnew StringBuilder(MAX_PATH);

             // GetShortPathName returns 0 when the operation fails
            if (NativeMethods::GetShortPathName(longPath, shortPathBuffer, shortPathBuffer->Capacity) == 0)
            {
                // Note: The constructor of Win32Exception will automatically
                // set Win32Exception.NativeErrorCode to Marshal.GetLastWin32Error()
                throw gcnew Win32Exception();
            }


            return shortPathBuffer->ToString();
        }
    };
}