参数可以是常量? [英] Can parameters be constant?

查看:190
本文介绍了参数可以是常量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在寻找的C#相当于Java的最后。 ?是否存在



C#有类似下面的东西:

 公共美孚(最终诠释吧); 

在上面的例子中,是一个只读变量,​​不能用更改美孚()。有什么办法在C#这样做吗?



举例来说,也许我还有很长的方法,将与 X 以Z 坐标某个对象(整数)的。我想是绝对肯定的是,函数不以任何方式改变这些值,从而造成数据损坏。因此,我想只读声明它们。

 公共美孚(INT X,INT Y,INT Z){
//做的东西
X ++; //哎呀。这会损坏数据。这可以在编译时被抓?
//做更多的东西,假设x是仍然是原来的值。
}


解决方案

可惜你不能做到这一点的C#。



常量 关键字只能用于局部变量和领域。



只读 关键字只能领域。




注:Java语言还支持有最终的参数的方法。此功能是在C#中不存在的。




从的 http://www.25hoursaday.com/CsharpVsJava.html


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

Does C# have anything like the following:

public Foo(final int bar);

In the above example, bar is a read only variable and cannot be changed by Foo(). Is there any way to do this in C#?

For instance, maybe I have a long method that will be working with x, y, and z coordinates of some object (ints). I want to be absolutely certain that the function doesn't alter these values in any way, thereby corrupting the data. Thus, I would like to declare them readonly.

public Foo(int x, int y, int z) {
     // do stuff
     x++; // oops. This corrupts the data. Can this be caught at compile time?
     // do more stuff, assuming x is still the original value.
}

解决方案

Unfortunately you cannot do this in C#.

The const keyword can only be used for local variables and fields.

The readonly keyword can only be used on fields.

NOTE: The Java language also supports having final parameters to a method. This functionality is non-existent in C#.

from http://www.25hoursaday.com/CsharpVsJava.html

这篇关于参数可以是常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆