Can parameters be constant?

后端 未结 9 1536
终归单人心
终归单人心 2020-12-24 04:39

I\'m looking for the C# equivalent of Java\'s final. Does it exist?

Does C# have anything like the following:

public Fo         


        
9条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-24 04:46

    This is now possible in C# version 7.2:

    You can use the in keyword in the method signature. MSDN documentation.

    The in keyword should be added before specifying a method's argument.

    Example, a valid method in C# 7.2:

    public long Add(in long x, in long y)
    {
        return x + y;
    }
    

    While the following is not allowed:

    public long Add(in long x, in long y)
    {
        x = 10; // It is not allowed to modify an in-argument.
        return x + y;
    }
    

    Following error will be shown when trying to modify either x or y since they are marked with in:

    Cannot assign to variable 'in long' because it is a readonly variable

    Marking an argument with in means:

    This method does not modify the value of the argument used as this parameter.

提交回复
热议问题