nullable 참조 형식을 사용하는 c # editorconfig CA1062 null 검사 유효성 검사 메서드 (guard 절용)

안데스

dotnetstandard 2.1솔루션에 작은 라이브러리 프로젝트를 만들었습니다 . Nullable Reference Types를 사용하여 테스트하고 싶습니다 . 이 과정에서 적절한 컴파일 오류와 경고를 받고 싶습니다.

TLDR; CA1062 코드 품질 설정을 .editorconfig올바르게 설정하는 방법을 알고 싶습니다 .

도서관 프로젝트

nuget프로젝트에 다음 패키지를 추가했습니다 .

<ItemGroup>
      <PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="2.9.8">
          <PrivateAssets>all</PrivateAssets>
          <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      </PackageReference>
      <PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="2.9.8">
          <PrivateAssets>all</PrivateAssets>
          <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      </PackageReference>
      <PackageReference Include="Microsoft.CSharp" Version="4.7.0" />
        <PackageReference Include="Ardalis.GuardClauses" Version="1.4.2" />
  </ItemGroup>

여기에는 다양한 코드 분석 패키지와 Steve Smith의 멋진 Guard Clauses 라이브러리가 포함됩니다.

<Nullable>enable</Nullable>프로젝트에서를 사용하여 Nullable 참조 유형이 활성화되었습니다 .

그리고 실제 세계에서 실제로 뭔가를 수행하는 멋진 구현이 될 클래스가 있습니다.

using System;
using MyGuards;

namespace EditorConfigIssues
{
    public static class TestEditorConfig
    {
        public static void TestMethod(MyParam input)
        {
            string x = input.Check;
            Console.WriteLine(x);
        }
    }

    public class MyParam
    {
        public MyParam(string check) => Check = check;

        public string Check { get; }
    }
}

가드 도서관 프로젝트

솔루션에서 나는 또 다른 dotnetstandard 2.1프로젝트 인 간단한 Guard 라이브러리를 추가했습니다 .

using System;

namespace MyGuards
{
    public static class FakeGuard
    {
        public static void Validate(object obj)
        {
            if (obj == null)
                throw new ArgumentNullException();
        }
    }
}

참고 : 이것은 GuardClauses 라이브러리와 경쟁하는 것이 아닙니다.

.editorconfig

.editorconfig다음 진단 검사를 통해 솔루션 루트에를 추가했습니다 .

dotnet_diagnostic.CA1062.severity = error
dotnet_code_quality.CA1062.exclude_extension_method_this_parameter = true

그래서 이것을 제자리에 놓고 컴파일하면 다음과 같은 결과를 얻습니다. 오류

그래서 모든 것이 지금까지 내가 예상 한대로입니다. 아직 경비원을 사용하지 않습니다.

문제 해결-Steve Smith의 Guard Library

따라서 오류를 제거하기 위해 Steve Smiths Guard Library의 guard 절을 구현해 보겠습니다.

따라서 다음을 추가합니다 TestEditorConfig.TestMethod.

Guard.Against.Null(input, nameof(input));

다음으로 조정하십시오 .editorconfig.

dotnet_code_quality.CA1062.null_check_validation_methods = Ardalis.GuardClauses.Guard.Against.Null

훌륭합니다. 모두 좋습니다. 오류가 사라졌습니다.초기 오류가 사라짐

문제 해결-나만의 가드 라이브러리

하지만 이제는 내 경비를 사용하고 싶습니다. 따라서 초기 가드 체크인을 다음 TestEditorConfig.TestMethod으로 대체합니다 .

FakeGuard.Validate(input);

null_check_validation_methods를 다음으로 바꿉니다 .editorconfig.

dotnet_code_quality.CA1062.null_check_validation_methods = FakeGuard.Validate

이제 오류가 다시 발생했습니다.
여기에 이미지 설명 입력

질문

  1. 문제는 동일한 솔루션의 경비원과 함께 프로젝트를 사용하려면 무엇이 필요합니까?
  2. 오류 창에서 다른 CA1062에 대한 경고가 표시되는 이유는 무엇입니까?
The keyword "dotnet_code_quality.CA1062.exclude_extension_method_this_parameter" is unknown
The keyword "dotnet_code_quality.CA1062.null_check_validation_methods" is unknown

이 링크 MS Docs Code Quality를 확인하고 다음을 포함하여 FakeGuard에 대한 다양한 조합을 시도했습니다.

  • MyGuards
  • MyGuards.FakeGuard
  • FakeGuard
  • MyGuards.FakeGuard.Validate
  • FakeGuard. 검증
  • 확인

흥미롭게도 다른 솔루션에서는 오류 창에서 CA1062 editorconfig 설정에 대한 불만이 없습니다. 그리고 거기에서 나는 일을 할 수 없었 null_check_validation_methods습니다. 따라서이 해결책을 모았습니다. 이것은 한두 달 동안 나를 괴롭 혔지만 마침내 그 순간에 모든 것을 통합 할 수있는 에너지를 얻었습니다.

EditorConfig 버그?

FakeGuard 파일을 Library 프로젝트에 복사하면 오류 메시지가 사라집니다. 그러나 이것이 솔루션의 다른 프로젝트에서 작동하지 않는 이유는 무엇입니까?

안데스

OK ... roslyn-analyzers문제 에 대해 게시했습니다 -여기-https: //github.com/dotnet/roslyn-analyzers/issues/3451

이것은 버그로 밝혀졌습니다. 현재 제안 된 해결 방법은 다음과 같습니다.

using System;

[AttributeUsage(AttributeTargets.Parameter)] 
internal sealed class ValidatedNotNullAttribute : Attribute { } 

namespace MyGuards
{
    /// <summary>
    /// Checks stuff.
    /// </summary>
    public static class FakeGuard
    {
        /// <summary>
        /// No more nulls.
        /// </summary>
        /// <param name="obj"></param>
        public static void Validate([ValidatedNotNull] object obj)
        {
            if (obj == null)
                throw new ArgumentNullException();
        }
    }
}

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관