简体   繁体   中英

c# cannot declare static and non static methods with same parameters?

If I try to declare static and non-static methods with the same parameters compiler returns an error: type 'Test' already defines a member called 'Load' with the same parameter types.

    class Test
    {
        int i = 0;

        public int I
        {
            get { return i; }
            set { i = value; }
        }

        public bool Load(int newValue)
        {
            i = newValue;
            return true;
        }

        public static Test Load(int newValue)
        {
            Test t = new Test();
            t.I = newValue;
            return t;
        }

As far as I know these two methods can not be mixed, non static method is called on object whereas static method is called on class, so why does compiler not allow something like this and is there a way to do something similar?

If your Test class had a method like this:

public void CallLoad()
{
    Load(5);
}

the compiler would not know which Load() to use. Calling a static method without the class name is entirely allowed for class members.

As for how to do something similar, I guess your best bet is to give the methods similar but different names, such as renaming the static method to LoadTest() or LoadItem() .

Inside the class itself, you call both instance methods and static methods without an instance or the class name, thus making the two undistinguishable if the names and parameters are the same:

class Test
{
    public void Foo()
    {
        Load(0); // Are you trying to call the static or the instance method?
    }

    // ...
}

The signature of a method is the combination of name and parameters (number and types).

In your case, your 2 methods have the same identical signature. The fact that one is static and other one is not makes no difference in accepting them as valid methods for the class.

I don't think so. if a non static method in this class calls Load(intValue). which method will be called?

Both methods have the same name, defined in the same class (scope) and with the same signature. C# does not allow this.

The problem is not related with writing this or the classname . C# specs allow you to call static methods using object instances:

AClass objectA = new AClass();
objectA.CallStaticMethod();

This code is valid so the compiler never has a way to know if you're calling a static or an instance method.

In C# a method cannot be overloaded by return type. It must at least have a different set of parameters, regardless if the method is static or not.

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