簡體   English   中英

從錯誤警告:從.Net 3.5升級到.Net 4.5時可能出現意外的參考比較

[英]Warning as Error: Possible unintended reference comparison when upgrading from .Net 3.5 to .Net 4.5

目前,我正在將WPF應用程序從.Net Framework 3.5遷移到.Net Framework 4.5。 .Net Framework升級之后,應用程序現在將編譯為64位而不是32位。 編譯應用程序時出現以下錯誤:

警告為錯誤:可能會進行意外的參考比較; 要進行值比較,請將左側的文字鍵入“ System.Type”

我的問題是:既然我已經升級到.Net 4.5,而從未在.Net 3.5上升級,為什么會出現此錯誤? 我沒有對項目的構建屬性進行任何更改,都將“ Treat warnings as errors設置設置為All 下面是產生錯誤的代碼,我添加了一些有關所做更改的注釋,未注釋的部分在.Net 4.5下編譯。

private void FoldersListBoxMouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    // Get typed sender
    ListBox typedSender = sender as ListBox;
    if (typedSender != null)
    {
        // Check if an item was double clicked
        //The line below worked in .Net 3.5, but not in .Net 4.5
        //if ((typedSender.SelectedItem != null) && (typedSender.InputHitTest(e.GetPosition(typedSender)) != typedSender.GetType()))
        //And this is the line that I have changed (I added GetType()!).
        if ((typedSender.SelectedItem != null) && (typedSender.InputHitTest(e.GetPosition(typedSender)).GetType() != typedSender.GetType()))
        {
            // Yes, set the new path
            SelectedPath = typedSender.SelectedValue as string;
        }
    }
}

編輯:我已經在將此代碼添加到應用程序中時進行了查找,但無法找到它,因為Subversion存儲庫僅可追溯到6年。

基本上,您先前的代碼已損壞。 您說它有效,但是我看不到該條件永遠是錯誤的。 我懷疑編譯器現在比以前更聰明。 條件是:

typedSender.InputHitTest(e.GetPosition(typedSender)) != typedSender.GetType()

現在, InputHitTest返回一個IInputElement類型的值。 因此條件(忽略第一部分)可以重寫為:

IInputElement element = typedSender.InputHitTest(e.GetPosition(typedSender));
Type type = typedSender.GetType();
if (element != type)
{
    ...
}

這兩個引用相等的唯一方法是,如果它們都為null ,並且typedSender.GetType()永遠不會返回null ,那么條件是毫無意義的。

現在,您正在比較命中測試結果的輸入元素是否與typedSender相同類型,這至少是有道理的-盡管它不會檢查它是否為 typedSender

值得注意的是, InputHitTest文檔包括:

通常不會從您的應用程序代碼中調用此方法。 僅當您打算重新實現大量已經存在的低級輸入功能(例如重新創建鼠標設備邏輯)時,才調用此方法是適當的。

確定要打電話嗎?

暫無
暫無

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

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