扩展方法的问题
我声明了以下扩展方法:
public static T FindAncestor<T>(DependencyObject obj) where T : DependencyObject
{
while (obj != null)
{
T o = obj as T;
if (o != null)
{
return o;
}
obj = VisualTreeHelper.GetParent(obj);
}
return null;
}
[System.Runtime.CompilerServices.Extension()]
public static T FindAncestor<T>(UIElement obj) where T : UIElement
{
return FindAncestor<T>((DependencyObject)obj);
}
它似乎不适用于 TextBlock
:
var csiPage = (sender as TextBlock).FindAncestor<NotebookPageView>();
NotebookPageView
继承自 UserControl
。
为什么扩展方法不可用?
I have declared the following extension method:
public static T FindAncestor<T>(DependencyObject obj) where T : DependencyObject
{
while (obj != null)
{
T o = obj as T;
if (o != null)
{
return o;
}
obj = VisualTreeHelper.GetParent(obj);
}
return null;
}
[System.Runtime.CompilerServices.Extension()]
public static T FindAncestor<T>(UIElement obj) where T : UIElement
{
return FindAncestor<T>((DependencyObject)obj);
}
It doesn't seem to work with TextBlock
:
var csiPage = (sender as TextBlock).FindAncestor<NotebookPageView>();
NotebookPageView
inherits from UserControl
.
Why isn't the extension method available?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这不是一个扩展方法。这只是一个静态方法。要使其成为扩展方法,您需要在参数上使用
this
关键字:另外,正如 @Jonathan 下面提醒的那样,扩展方法需要位于静态类中,因此请确保您的代码。
有关详细信息,请参阅有关扩展方法的 MSDN 文档。
That's not an extension method. It's just a static method. To make it an extension method you need to use the
this
keyword on the parameter:Also, as @Jonathan reminds below, extension methods need to be in a static class, so make sure that's the case in your code.
For more information see the MSDN documentation on extension methods.