2012-12-17 33 views
4

我試圖使這種擴展方法。在演員表示'不能將T型轉換爲MouseEventArgs'時出錯。我不應該能夠上傳對象(因爲MouseEventArgs : InputEventArgs)?無法投入InputEventArgs MouseEventArgs

如果您好奇,我正在使用它來通過在處理程序方法中使用基本InputEventArgs來共享Mouse和Touch事件之間的事件處理程序。

public static class InputEventArgsExtensions 
    { 
     public static Point GetPosition<T>(this T e, IInputElement obj) 
      where T : InputEventArgs 
     { 
      if (e is MouseEventArgs) 
       return ((MouseEventArgs)e).GetPosition(obj); 
      else if (e is TouchEventArgs) 
       return ((TouchEventArgs)e).GetTouchPoint(obj).Position; 

      return new Point(); 
     } 
    } 
+0

啊那好。不幸的是,名稱選擇不當並不能解決問題。 –

+0

對不起;是的,我意識到這不是一個問題後刪除了評論。 –

+0

看看這個鏈接:http://stackoverflow.com/questions/183923/compiler-fails-converting-a-constrained-generic-type – itsme86

回答

1

我想這樣做的,它爲我工作。

public static class InputEventArgsExtensions 
    { 
     public static Point GetPosition<T>(this T e, IInputElement obj) 
      where T : InputEventArgs 
     { 
      if (e is MouseEventArgs) 
       return (e as MouseEventArgs).GetPosition(obj); 
      else if (e is TouchEventArgs) 
       return (e as TouchEventArgs).GetTouchPoint(obj).Position; 

      return new Point(); 
     } 
    } 
+0

天才!完美的作品。 –

0

如果使用電子將始終從InputEventArgs派生,那麼就使用該類型,而不是一個通用的方法:

public static Point GetPosition(this InputEventArgs e, IInputElement obj) 
{ 
    // Code here 
} 
+0

這是一個很好的觀點,但它對錯誤沒有幫助。 –

0

MouseEventArgs已經有GetPosition方法。所以我認爲這只是TouchEventArgs,你可能想要擴展:

public static Point GetPosition(this TouchEventArgs e, IInputElement relativeTo) 
{ 
    e.GetTouchPoint(obj).Position; 
} 
+0

也許,但我使用擴展方法的代碼中只有InputEventArgs類型。 –

+0

順便說一句,還有StylusEventArgs,你可能應該考慮 –

+0

呃。感謝您的支持,如果我現在不做,它無疑會成爲我未來某個時間的錯誤報告。 –

相關問題