开发者

compile time error occurs when converting an extension method into a generic method

I have an extension method here like this:

public static class Extensions
{
    public static System.Windows.DependencyObject SetToolTip(this System.Windows.DependencyObject element, object value)
    {
        System.Windows.Controls.ToolTipService.SetToolTip(element, value);
        return element;
    }
}

now when I convert it into a generic method. I get en compile time error. Error 1 Cannot convert type 'System.Windows.DependencyObject' to开发者_Go百科 'T' Extensions.cs 149 16

public static class Extensions
{
    public static T SetToolTip<T>(this System.Windows.DependencyObject element, object value)
    {
        System.Windows.Controls.ToolTipService.SetToolTip(element, value);
        return (T)element;
    }
}

any ideas how to resolve this issue?


public static T SetToolTip<T>(
       this System.Windows.DependencyObject element, object value)
       where T : System.Windows.DependencyObject
{
    System.Windows.Controls.ToolTipService.SetToolTip(element, value);
    return element as T;
}

or even better

public static T SetToolTip<T>(
       this T element, object value)
       where T : System.Windows.DependencyObject
{
    System.Windows.Controls.ToolTipService.SetToolTip(element, value);
    return element;
}

(not sure about the last; EDIT: checked, it works.)


It seems you are just returning the input element, so you should be able to change your method to:

public static T SetToolTip<T>(this T element, object value) where T : DependencyObject
{
    ToolTipService.SetToolTip(element, value);
    return element;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜