program story

Guid.IsNullOrEmpty () 메서드가없는 이유

inputbox 2020. 8. 26. 07:49
반응형

Guid.IsNullOrEmpty () 메서드가없는 이유


이것은 .NET의 Guid에 IsNullOrEmpty()메서드 가없는 이유가 궁금합니다 (비어 있으면 모두 0을 의미 함).

REST API를 작성할 때 ASP.NET MVC 코드의 여러 위치에서 필요합니다.

아니면 인터넷에서 아무도 같은 것을 요청하지 않았기 때문에 내가 뭔가를 놓치고 있습니까?


Guid값 유형 이므로 유형 의 변수는 Guidnull로 시작할 수 없습니다. 빈 GUID와 동일한 지 알고 싶다면 다음을 사용할 수 있습니다.

if (guid == Guid.Empty)

한 가지는 Guidnullable이 아닙니다. 다음을 확인할 수 있습니다.

myGuid == default(Guid)

이는 다음과 같습니다.

myGuid == Guid.Empty

다음은 nullable Guid에 대한 간단한 확장 메서드입니다.

/// <summary>
/// Determines if a nullable Guid (Guid?) is null or Guid.Empty
/// </summary>
public static bool IsNullOrEmpty(this Guid? guid)
{
  return (!guid.HasValue || guid.Value == Guid.Empty);
}

최신 정보

정말로 이것을 모든 곳에서 사용하고 싶다면 일반 Guid에 대한 다른 확장 메서드를 작성할 수 있습니다. null이 될 수 없기 때문에 어떤 사람들은 이것을 좋아하지 않을 것입니다 ... 그러나 그것은 당신이 찾고있는 목적에 부합하고 당신이 Guid와 함께 일하고 있는지 알 필요가 없습니까? 또는 Guid (리팩토링 등에 적합).

/// <summary>
/// Determines if Guid is Guid.Empty
/// </summary>
public static bool IsNullOrEmpty(this Guid guid)
{
  return (guid == Guid.Empty);
}

이제 someGuid.IsNullOrEmpty();Guid 또는 Guid?를 사용 하는 모든 경우에 사용할 수 있습니다 .

내가 말했듯이 어떤 사람들은 IsNullOrEmpty()값이 null이 될 수 있다는 것을 암시 하기 때문에 이름 지정에 대해 불평 할 것입니다. 당신이 정말로 원한다면, 같은 확장에 다른 이름으로 와서 IsNothing()IsInsignificant()또는 무엇이든 :)


Guid에 대한 확장 메서드를 만들어 IsEmpty 기능을 추가 할 수 있습니다.

public static class GuidEx
{
    public static bool IsEmpty(this Guid guid)
    {
        return guid == Guid.Empty;
    }
}

public class MyClass
{
    public void Foo()
    {
        Guid g;
        bool b;

        b = g.IsEmpty(); // true

        g = Guid.NewGuid();

        b = g.IsEmpty; // false

        b = Guid.Empty.IsEmpty(); // true
    }
}

이 말은 항상 이런 말을 봅니다

Guid is a value type, so a variable of type Guid can't be null to start with

but it is just NOT TRUE.

Agreed you can not programmatic set a Guid to null, but when some SQL pulls in a UniqueIdentifier and maps it to a Guid, and if that value is null in the db, the value comes up as null in the C#.

참고URL : https://stackoverflow.com/questions/9837602/why-isnt-there-a-guid-isnullorempty-method

반응형