简体   繁体   中英

how to use non static method inside other class without creating object in C#

I have recently changed my project a little to include an interface for better integration. I'm really stuck with how to access a method on one form (which is used for updating form controls) from my class which is inheriting from my interface. here below is a few snippets of code that should help with clarity.

 //this is the double click event from where i have to call SelectDeal method

   private void TodayEventsGridView_DoubleClick(object sender, EventArgs e)

    {
        DealModule _dealModule = new DealModule();

        // i dont want to create an obect of class DealModule()
        try
        {
            this.Cursor = Cursors.WaitCursor;
            _dealModule.SelectDeal(DealKey);

        }
        catch (Exception ex)
        {
            MessageBox.Show("Warning: " + this.ToString() + " " + System.Reflection.MethodInfo.GetCurrentMethod().Name + "\n" + ex.Message, ex.GetType().ToString());
        }
        finally
        {
            this.Cursor = Cursors.Default;
        }
    }

This is, by definition, impossible. Instance (non-static) methods can only be used when you have an instance of the class to work with. You either need to use an instance of your class, or declare the method static.

As Patrick says below, the fact you are trying to do this probably indicates a design flaw, but it's difficult to suggest how to improve it without more context.

I would add that in the general case, from a design point of view it's preferable to call against instances of a class (or, better, an interface) rather than static methods. This increases testability and helps you achieve loose coupling, making your software easier to maintain. Why do you think that calling a static method is more preferable in your case?

If you want to access SelectDeal without an instance of DealModule you need to mark SelectDeal as static .

Eg:

public class DealModule
{
    // other code

    public static void SelectDeal(Key dealKey) ( /* ... */ }
}

If a method is not marked static you can't access it without an instance.
BUT as you can't have static methods in an interface you may want to work around this using eg a singelton:

public class DealModule
{
    private static DealModule instance = null;
    public static DealModule Instance
    {
        get
        {
            if (instance == null)
                instance = new DealModule();
            return instance;
        }
    }
    // other code

    public void SelectDeal(Key dealKey) ( /* ... */ }
}

and then

DealModule.Instance.SelectDeal(DealKey);

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