In C#, how can I find if a given object has a specific ancestor?
For example, say I have the following class structure.
ContainerControl | +----> Form | +--> MyNormalForm | +--> MyCustomFormType | +---> MyCustomForm
If I have a method like this:
v开发者_开发百科oid MyCoolMethod (Form form)
How do I find if form descends from MyCustomFormType or not?
if (form is MyCustomFormType) {
// form is an instance of MyCustomFormType!
}
if( form is MyCustomFormType)
If you are going to cast it to that type you should use the as operator and check for null.
MyCustomFormType myCustomFormType = form as MyCustomFormType;
if( myCustomFormType != null)
{
// this is the type you are looking for
}
As any number of respondents have added: through the is
(or as
) operators.
However, wanting to find out the exact type is a classic code smell. Try not to do that. If you want to make decisions based on the exact type of form, try instead to put that logic in overridden virtual methods rather than outside your class.
The is
operator:
bool isOk = form is MyCustomForm;
Use the is
operator.
e.g.
if (form is MyCustomFormType) {
do whatever
}
void MyCoolMethod (Form form) {
if (form is MyCustomFormType)
// do your cool stuff here
}
var myCustomForm = form as MyCustomFormType;
if(myCustomForm != null)
{
// form was a MyCustomFormType instance and you can work with myCustomForm
}
Avoid is
if you want to manipulate the form as a MyCustomFormType. By using as, you only need one cast.
精彩评论