使用Entity Framework创建索引,代码如下:
var op = new CreateIndexOperation
{
Columns = { "COL_A", "COL_B", "COL_C" },
IsUnique = true,
Name = "INDEX_NAME",
Table = "TABLE_NAME"
});
这会按预期进行编译和工作。尝试将其重构为以下方法(针对此示例进行了简化):
private void AddIndex(params string[] columns)
{
var op = new CreateIndexOperation
{
Columns = columns.ToList(),
IsUnique = true,
Name = "INDEX_NAME",
Table = "TABLE_NAME"
});
}
此方法抛出以下编译器错误:
Property or Indexer 'IndexOperation.Columns' cannot be assigned to -- it is read only
查看 MSDN documentation ,这似乎是正确的,并且 Columns
属性没有 setter。但是,如果是这种情况,为什么第一段代码没有抛出编译器错误,而第二段代码却抛出了我试图从变量设置此值的地方?
最佳答案
这是因为在使用第一个代码时,您使用的是 collection-initializer ,其中第二个示例使用经典的 setter 方法(当然不存在)。这意味着在第一个例子中你实际上是这样调用的:
var op = new CreateIndexOperation();
op.Columns.Add(...);
op.IsUnique = true;
op.Name = "INDEX_NAME";
op.Table = "TABLE_NAME";
如您所见,您没有设置属性,而是对getter 返回的对象调用方法。
这当然假设 Columns
是在类的构造函数中初始化的。否则你会得到一个 NullReferenceException
。
然而,第二个代码编译成这样:
var op = new CreateIndexOperation();
op.Columns = columns.ToList();
op.IsUnique = true;
op.Name = "INDEX_NAME";
op.Table = "TABLE_NAME";
关于c# - 为只读属性赋值适用于固定值,但不适用于变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43121869/