使用方法不变变量的初始化(C#) [英] initializing of constant variable using method (C#)
本文介绍了使用方法不变变量的初始化(C#)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以使用另一个类
namespace ConsoleApplication1
{
class Program
{
const int gravit = haha.habc();//something like this
static void Main(string[] args)
{
some codes.....
}
public class haha
{
int gar = 1;
public int habc()
{
int sa = 1;
return sa;
}
}
}
}
例如像上面的代码(FYI与此代码我得到表达被分配到......必须恒定),如果不是有其他的方法做一些类似的。
For example like the codes above(FYI with this code I am getting Expression being assigned to ... must be constant), if not is there other method to do something similar to this.
推荐答案
没有,那是不可能的,你可以使用只读
字段,而不是因为常数值应该在编译知道 - 时间:
No, that's not possible, you could use readonly
field instead because constant values should be known at compile-time:
private static readonly int gravit = haha.habc();//something like this
注: habc
如果你想将它命名方法应该是静态的这种方式。
NOTE: the habc
method should be static if you want to call it that way.
这篇关于使用方法不变变量的初始化(C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文