简体   繁体   中英

How can i make and call a method without any paramaters?

I want to simply call my method like this: collect.clear; instead of, collect.clear();

in other words, I want to make this method

    class collect
    {
       public List<string> list = new List<string>();
       public void Clear()
       {
           list.clear();
       }
    }

to be called like so

    static void Main(string[] args)
    {
        collect.clear;
    }

is this possible or not at all.

I want to simply call my method like this: collect.clear; instead of, collect.clear();

Well, frankly: you don't get to decide what the language syntax is, and in C#, the syntax for invoking a method is: collect.clear(); .

Basically, you can't do what you want. You could make it a property, but then you'd need to discard the result (so it can choose between get and set ), ie with a property get called clear , _ = collect.clear; - frankly I think that's a step back from the () . It is also a terrible idea from the basis of unexpected side-effects; most UI elements (including the debugger) and libraries (serializers, etc) think that they can freely evaluate property gets, so it would be very unexpected it reviewing a property had the side effect of clearing the data! Basically, don't do that.

So; embrace the () . They express the intent here, for your benefit, the benefit of people reviewing/maintaining it, and for the benefit of the compiler.

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