C # constlà chính xác giống như của Java final, ngoại trừ nó hoàn toàn luôn luôn static. Theo tôi, không thực sự cần thiết cho một constbiến là không static, nhưng nếu bạn cần truy cập vào một constbiến không phải static, bạn có thể làm:
class MyClass
{
private const int myLowercase_Private_Const_Int = 0;
public const int MyUppercase_Public_Const_Int = 0;
/*
You can have the `private const int` lowercase
and the `public int` Uppercase:
*/
public int MyLowercase_Private_Const_Int
{
get
{
return MyClass.myLowercase_Private_Const_Int;
}
}
/*
Or you can have the `public const int` uppercase
and the `public int` slighly altered
(i.e. an underscore preceding the name):
*/
public int _MyUppercase_Public_Const_Int
{
get
{
return MyClass.MyUppercase_Public_Const_Int;
}
}
/*
Or you can have the `public const int` uppercase
and get the `public int` with a 'Get' method:
*/
public int Get_MyUppercase_Public_Const_Int()
{
return MyClass.MyUppercase_Public_Const_Int;
}
}
Chà, bây giờ tôi nhận ra câu hỏi này đã được hỏi 4 năm trước, nhưng vì tôi đã dành khoảng 2 giờ làm việc, bao gồm thử tất cả các cách trả lời và định dạng mã khác nhau, vào câu trả lời này, tôi vẫn đăng nó. :)
Nhưng, đối với hồ sơ, tôi vẫn cảm thấy hơi ngớ ngẩn.