我有这个代码;
using System;
namespace Rapido
{
class Constants
{
public static const string FrameworkName = "Rapido Framework";
}
}
Run Code Online (Sandbox Code Playgroud)
Visual Studio告诉我: The constant 'Rapido.Constants.FrameworkName' cannot be marked static
如何在不创建新实例的情况下从其他类中获取此常量?(即通过直接访问它Rapido.Constants.FrameworkName)
我想在属性参数中放置一个恒定的日期时间,如何创建一个恒定的日期时间?它与ValidationAttributeEntLib验证应用程序块的一个相关,但也适用于其他属性.
当我这样做:
private DateTime _lowerbound = new DateTime(2011, 1, 1);
[DateTimeRangeValidator(_lowerbound)]
Run Code Online (Sandbox Code Playgroud)
我去拿:
An object reference is required for the non-static field, method, or property _lowerbound
Run Code Online (Sandbox Code Playgroud)
通过这样做
private const DateTime _lowerbound = new DateTime(2011, 1, 1);
[DateTimeRangeValidator(_lowerbound)]
Run Code Online (Sandbox Code Playgroud)
我去拿:
类型'System.DateTime'不能声明为const
有任何想法吗?走这条路不是首选:
[DateTimeRangeValidator("01-01-2011")]
Run Code Online (Sandbox Code Playgroud) 我使用了几个常量,我的计划是将它们放在const数组的双精度数中,但是编译器不会让我这么做.
我试过这样声明:
const double[] arr = {1, 2, 3, 4, 5, 6, 73, 8, 9 };
Run Code Online (Sandbox Code Playgroud)
然后我决定将其声明为静态只读:
static readonly double[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9};
Run Code Online (Sandbox Code Playgroud)
但问题仍然存在.为什么编译器不允许我声明一个const值数组?或者它会,我只是不知道如何?
在C中,我是否更喜欢常量而不是定义?我最近阅读了很多代码,所有的例子都大量使用了定义.
是什么const在"顶级"预选赛中,C平均++?
还有什么其他水平?
例如:
int const *i;
int *const i;
int const *const i;
Run Code Online (Sandbox Code Playgroud) 在编写以下函数时abs,我收到错误:
非成员函数unsigned int abs(const T&)不能有cv-qualifier.
template<typename T>
inline unsigned int abs(const T& t) const
{
return t>0?t:-t;
}
Run Code Online (Sandbox Code Playgroud)
删除const函数的限定符后,没有错误.由于我没有t在函数内部进行修改,因此上面的代码应该编译.我想知道为什么我得到错误?
const这些天我对关键词非常恼火,因为我对它并不熟悉.我有一个存储所有const指针的向量vector<const BoxT<T> *> *Q_exclude,并且在另一个类的构造函数中,我需要将此队列中的一个元素作为参数传入并将其分配给非const成员.我的问题是:
如何将const变量分配给非const变量?我知道这没有意义,因为毕竟const是一个const,不应该被改变.但是在这个过程中必须改变那个恼人的成员变量REALLY!我也可能会将向量中的数据类型更改为非const,但这样做太多了.或者有谁知道如何避免这种情况?
我不明白我的C++类中这两个语句之间的区别:
class MyClass {
public:
private:
const static int var = 0; // Option 1
static const int var = 0; // Option 2
};
Run Code Online (Sandbox Code Playgroud)
b/w选项1和选项2有什么区别?他们都编译.
要提取常量,我可以使用ctrl+ alt+ c,即"提取"创建公共常量:
public static final String CONST = "123";
Run Code Online (Sandbox Code Playgroud)
所以我需要手动键入private.有没有办法默认使用私有范围提取常量?
我在Stroustrup的一本书中找到了这段代码:
void print_book(const vector<Entry>& book)
{
for (const auto& x : book) // for "auto" see §1.5
cout << x << '\n';
}
Run Code Online (Sandbox Code Playgroud)
但const似乎是多余的,因为x会被推断为一个const_iterator,因为book是const在参数.是const auto真的更好吗?