簡體   English   中英

檢測 C# 中的可空類型

[英]Detecting nullable types in C#

我有一個這樣定義的方法:

public bool IsValid(string propertyName, object propertyValue)
{
  bool isValid = true;
  // Validate property based on type here
  return isValid;
}

我想做類似的事情:

if (propertyValue is bool?)
{
  // Ensure that the property is true
}

我的挑戰是,我不確定如何檢測我的 propertyValue 是否為可為空的布爾值。 有人可以告訴我該怎么做嗎?

謝謝!

propertyValue的值永遠不能是Nullable<bool> 由於propertyValue的類型是object ,任何值類型都將被裝箱......如果你裝箱一個可為空的值類型值,它成為 null 引用,或底層不可為空類型的裝箱值。

換句話說,您需要在不依賴的情況下找到類型......如果您可以為我們提供更多關於您想要實現的目標的背景信息,我們可能會為您提供更多幫助。

您可能需要為此使用 generics 但我認為您可以檢查 propertyvalue 的可為空的基礎類型,如果它是 bool,它就是一個可為空的 bool。

Type fieldType = Nullable.GetUnderlyingType(typeof(propertyvalue));
if (object.ReferenceEquals(fieldType, typeof(bool))) {
    return true;
}

否則嘗試使用泛型

public bool IsValid<T>(T propertyvalue)
{
    Type fieldType = Nullable.GetUnderlyingType(typeof(T));
    if (object.ReferenceEquals(fieldType, typeof(bool))) {
        return true;
    }
    return false;
}

這可能是一個長鏡頭,但是您可以使用 generics 和方法重載讓編譯器為您解決這個問題嗎?

public bool IsValid<T>(string propertyName, T propertyValue)
{
    // ...
}

public bool IsValid<T>(string propertyName, T? propertyValue) where T : struct
{
    // ...
}

另一個想法:您的代碼是否試圖通過 object 上的每個屬性值來 go? 如果是這樣,您可以使用反射來遍歷屬性,並以這種方式獲取它們的類型。

編輯

正如Denis在他的回答中建議的那樣使用Nullable.GetUnderlyingType可以解決使用重載的需要。

暫無
暫無

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

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