如何访问const变量? [英] How to access const variable ?
本文介绍了如何访问const变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我运行此代码时,我得到的ClassA不存在。我如何访问const int aaa?
code
when i run this code i get ClassA does not exists. how do i access const int aaa ?
code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace const2
{
public class ClassA
{
public const int aaa = 10;
}
class Program
{
static void Main(string[] args)
{
ClassA classaa = new ClassA();
Console.WriteLine(classA.aaa);
Console.ReadKey();
}
}
}
推荐答案
这里有一些问题:主要是做C#区分大小写:classA与ClassA不同,因此您无法在不获取类名的情况下访问const
值:
There are a few things wrong here: mainly to do with C# being case sensitive: "classA" is not the same as "ClassA", so you can't access theconst
value without getting the class name right:
ClassA classaa = new ClassA();
Console.WriteLine(ClassA.aaa);
因为它是 const
值,它是隐式静态 - 所以你不能通过类实例访问它,只能通过类名。因此,您声明的实例是不必要的,因为这也不会起作用:
Because it is a const
value, it is implicitly static - so you can't access it via a class instance, only via the class name. So the instance you declare is unnecessary, as this won't work either:
ClassA classaa = new ClassA();
Console.WriteLine(classaa.aaa);
拼写错误,第一个字符是大写的
spell error, first char is in uppercase
Console.WriteLine(ClassA.aaa);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace const2
{
public static class ClassA
{
public const int aaa = 10;
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine(aaa);
}
}
}
未经测试,但准确访问常量。
Untested, but accurate for accessing the const.
这篇关于如何访问const变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文