메서드 결과를 무시하지 마십시오.
업데이트: 2007년 11월
TypeName |
DoNotIgnoreMethodResults |
CheckId |
CA1806 |
범주 |
Microsoft.Usage |
변경 수준 |
주요 변경 아님 |
원인
새 개체를 만들었지만 사용하지 않은 경우
- 또는 -
새 문자열을 만들어 반환하는 메서드를 호출했지만 새 문자열이 사용되지 않은 경우
- 또는 -
COM 또는 P/Invoke 메서드가 반환하는 HRESULT 또는 오류 코드가 사용되지 않은 경우
규칙 설명
이 규칙은 코드에 다음과 같은 상황이 발생할 때 이를 인식하는 데 도움이 됩니다.
불필요한 개체를 생성하고 이와 연관된 사용되지 않는 개체를 가비지 수집하면 성능이 저하됩니다.
문자열은 변경할 수 없으며 ToUpper 등의 메서드는 호출하는 메서드의 문자열 인스턴스를 수정하는 대신 문자열의 새 인스턴스를 반환합니다.
HRESULT 또는 오류 코드를 무시하면 예기치 않은 동작으로 인해 오류가 발생하거나 리소스가 부족해질 수 있습니다.
위반 문제를 해결하는 방법
메서드 A가 B 개체의 새 인스턴스를 만들었지만 인스턴스가 사용되지 않은 경우 인스턴스를 다른 메서드에 인수로 전달하거나 인스턴스를 변수에 할당합니다. 개체를 만들 필요가 없는 경우에는 개체를 제거합니다.
- 또는 -
메서드 A가 메서드 B를 호출하지만 메서드 B에서 반환되는 새 문자열 인스턴스를 사용하지 않은 경우 인스턴스를 다른 메서드에 인수로 전달하거나, 인스턴스를 변수에 할당하거나, 불필요한 경우 호출을 제거합니다.
- 또는 -
메서드 A에서 메서드 B를 호출하지만 메서드가 반환하는 HRESULT 또는 오류 코드를 사용하지 않는 경우 조건문에서 결과를 사용하거나, 결과를 변수에 할당하거나, 다른 메서드에 인수로 전달합니다.
경고를 표시하지 않는 경우
특정한 용도로 개체를 만드는 경우 이외에는 이 규칙에서 경고를 표시하십시오.
예제
다음 예제에서는 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; }
}
};
}
다음 예제에서는 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
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; }
}
};
}
다음 예제에서는 생성된 개체를 사용하지 않는 메서드를 보여 줍니다.
참고: |
---|
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();
}
};
}
다음 예제에서는 필요하지 않은 개체를 생성하지 않는 방법으로 위에 나와 있는 규칙 위반을 해결합니다.
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();
}
};
}
다음 예제에서는 네이티브 메서드 GetShortPathName이 반환하는 오류 코드를 무시하는 메서드를 보여 줍니다.
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();
}
};
}
다음 예제에서는 오류 코드를 검사하고 호출에 실패할 때 예외를 throw하여 위에 나와 있는 규칙 위반을 해결합니다.
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();
}
};
}