簡體   English   中英

為什么我不能寫if(object是HashSet <>)但是如果我寫的話就沒關系(object.GetType()== typeof(HashSet <>))

[英]Why can't I write if (object is HashSet<>) but it's okay if I write (object.GetType() == typeof(HashSet<>))

標題說明了一切,這里有一些格式:

為什么我不能寫

public bool IsHashSet(object obj)
{
    return obj is HashSet<>;
}

但這沒關系:

public bool IsHashSet(object obj)
{
    return obj.GetType() == typeof(HashSet<>);
}

所有泛型都是如此,並且不限於HashSet

你的功能

public bool IsHashSet(object obj)
{
  return obj.GetType() == typeof(HashSet<>);
}

將為obj每個可能值返回false ,除了null ,在這種情況下它將拋出NullReferenceException 不會檢查obj是否是哈希集。 typeof(HashSet<int>)typeof(HashSet<>)是兩種不同的類型。

出於同樣的原因, obj is HashSet<>被拒絕。 這完全沒用。 這兩個函數之間的唯一區別是,一個在編譯器知道的方式中是無用的,另一個在編譯器不知道的方式中是無用的。

您可以使用type.IsGenericTypetype.GetGenericTypeDefinition() ,然后將后者的結果與typeof(HashSet<>) 但是,您應該問自己這是否有用:如果obj是從HashSet<int>派生的,則obj is HashSet<int>也會計算為true 使用obj.GetType()需要您自己檢查類層次結構。

您可以編寫一個可重用的輔助函數來檢查其他泛型類型:

public static bool IsInstanceOfGenericType(object obj, Type genericType) {
  if (obj == null)
    return false;

  var type = obj.GetType();
  while (type != null) {
    if (type.IsGenericType && type.GetGenericTypeDefinition() == genericType)
      return true;

    type = type.BaseType;
  }
  return false;
}

您可以將其稱為IsInstanceOfGenericType(someObject, typeof(HashSet<>))

回應你的意見:

在我對HashSet<>理解中,將意味着任何泛型的HashSet ,所以也許這將工作typeof(HashSet<>).IsAssignableFrom(HashSet<int>)

它不會。 您可能正在考慮使用Java,據我所知它確實有類似的東西,但C#卻沒有。 HashSet<int>HashSet<>是相關類型,但它們的關系不是與繼承相關的關系。

如果不是HashSet<>的含義

在獲得任何特定類型參數之前,它是HashSet<T>類型。 它可用於構造實數類型,例如在var t = typeof(int); typeof(HashSet<>).MakeGenericType(t)可用於獲取typeof(HashSet<int>) 如果在編譯時不知道t那將非常有用。 但是在這種動態類型構造之外,它沒有意義。

為什么在typeof()寫入是有效的但不是在is HashSet<>

它與is HashSet<>無效,因為它永遠不會有意義。 構造任何類型為HashSet<>對象是不可能的。

兩者都沒有實際工作,只是第一個在編譯時會失敗。 你可能想要的是這樣的:

public bool IsHashSet(object obj)
{
    if (obj != null) 
    {
        var t = obj.GetType();
        if (t.IsGenericType) {
            return t.GetGenericTypeDefinition() == typeof(HashSet<>);
        }
    }
    return false;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM