开发者

Can I identify the sub class from a base class parameter?

Take a look at the following. The question near the end of the code - in the "whoAmI" function...

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
u开发者_JAVA百科sing System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MY_TEST_PROJECT
{
    // a form class
    public partial class frmTestForm1 : Form
    {
        // zillion lines of code

        private void aFunction()
        {        
            ClassTest.whoAmI(this);
        }

        // zillion lines of code
    }

    // another form class...
    public partial class frmTestForm2 : Form
    {
        // zillion lines of code

        private void aFunction()
        {        
            ClassTest.whoAmI(this);
        }

        // zillion lines of code
    }

    // a home made test class
    public static class ClassTest
    {
        // zillion lines of code

        public static void whoAmI(Form theForm)
        {
            // IS THERE A WAY TO SEE WHAT KIND OF FORM theForm IS?

            // LIKE:
            // if (theForm IS A frmTestForm1)
            //   doThis();
            // else if (theForm IS A frmTestForm2)
            //   doThat();
        }

        // zillion lines of code
    }
}


You can check with the keyword is.

Also, you might want to solve your problem using polymorphism instead of checking the type.


There are few ways you can do this:

  • as you have guessed you can use "is" key word as Sjoerd has proposed
if (theForm is frmTestForm1)
   doThis();
//So on
  • Another approach is to use reflection to get the exact type of the form you have. Your code should look like somthing like this:

if (theForm.GetType().UnderlyingSystemType == typeof(frmTestForm1)) doThis();

The drawback of the first approach is that if, for example, your frmTestForm2 is derivative of frmTestForm1 and you use code like this if(yourform is frmTestForm1) and your form is pointing to a frmTestForm2 instance "is" keyword will return true.


Did you try this and it is not working? There is no problem trying to get a type from an object. Although you are sending it in as the base type the object still is a derived class type.


if (theForm.GetType().ToString() == typeof(frmTestForm1).ToString())
{
    // Do your stuff
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜