简体   繁体   中英

Casting type to object in C#

I have a function I want to make generic to display forms. I want the function to check if the form is opened already and if so bring it to the top if not create a new instance of the form and show it.

The first part of checking if the form is open is all good but I am having casting from T and creating a new form object of type T. I have used this line of code to create an instance of the form obj = Activator.CreateInstance<T>(); but it does not show all the methods and properties in intellisense. Where as the code Form x = new Form1. x Form x = new Form1. x will show all the methods and properties.

I am sure I am doing something wrong here any shine some light for me please.

     private static void ShowForm<T>(  )
    {
        T obj = default( T );

        List<T> opened = FormManager.GetListOfOpenForms<T>();
        if ( opened.Count == 0 )
        {
            // not opened

            // obj does not show all properties and methods
            obj = Activator.CreateInstance<T>();


            // x shows all properties and methods
            frmLogin x = new frmLogin();

        }
        else
        {
            // opened

        }

    }

You need to constrain T to inherit Form :

private static void ShowForm<T>() where T : Form, new()

Once the compiler knows that T is guaranteed to inherit Form , you'll be able to use all members defined in Form or its base classes.

The more general answer to your question would be to cast obj to Form .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM