I am learning WPF and there's a piece of code which I don't quite understand the method declared with constraints:
public static T FindAncestor<T>(DependencyObject dependencyObject)
where T : class // Need help to interpret this method declaration
I understand this is a shared method and T has be a class but what is what is 'static T FindAncestor'? Having troubles interpreting it as a whole. Thanks!
Code:
public static class VisualTreeHelperExtensions
{
public static T FindAncestor<T>(DependencyObject dependencyObject)
where T : class // Need help to interpret this method
{
DependencyObject target = dependencyObject;
do
{
target = VisualTreeHelper.GetParent(target);
}
while (target != null && !(target is T));
r开发者_如何学Goeturn target as T;
}
}
The static
keyword in front means that you do not have to instantiate VisualTreeHelperExtensions
in order to call the FindAncestor
method. You can say:
VisualTreeHelperExtensions.FindAncestor<MyClass>(myObj);
Where myObj
is a DependencyObject
. The where
, as you said, makes sure that T
(MyClass
in this case) is indeed a class
For convenience, Methods like this can be declared like this:
public static T FindAncestor<T>(this DependencyObject dependencyObject)
where T : class // Need help to interpret this method declaration
Which would allow you to call the method like so:
myObj.FindAncestor<MyClass>();
Effectively adding a method to your DependencyObject
after the fact.
The T
is a placeholder for a type - what is known as a generic. The where
clause is a generic constraint that requires reference types.
Hope I understand your question.
It's a declaration of public static function.
If it's not you're asking for, please explain better.
It means that it is a static method (you can call it without an instance of the class created) that returns an object of type T. FindAncestor
is the name of the method.
精彩评论