可选参数"必须是一个编译时常"是一个、可选、参数、QUOT

2023-09-04 00:04:53 作者:孤寂的灵魂

我有一类两部分文件划分,如:

I have a class divided in two partial files, like this:

public partial class PersonRepository : BaseRepository<Person>
{
    public static readonly string ColumnID = "ID";
    ...

public partial class PersonRepository : BaseRepository<Person>
{
    public List<Person> GetByCompany(int companyID, string sortExpression = ColumnID)
    {
    ...

但是编译器口口声声说 SORTEX pression 必须是一个编译时间常数。对我来说,似乎是一个完美的编译时间常数,所以我不明白问题出在哪里。

But the compiler keeps saying that sortExpression "must be a compile-time constant". To me it seems a perfect compile-time constant, so I don't understand where the problem is.

感谢您的帮助!

亚历山德罗

推荐答案

没有,前pression PersonRespository.ColumnID 不属于编译时间常数。这位前pressionID是,但是这不是你用什么作为默认参数。

No, the expression PersonRespository.ColumnID is not classified as a compile-time constant. The expression "ID" is, but that's not what you're using as the default parameter.

特别是,如果 Col​​umnID的是只是一个正常的领域,那么任何对它的引用将得到解决的为的一个领域 - 所以,如果你编译它指的是现场组装,然后更改值,并重建包含的组件 PersonRepository ,引用组件的将会的看到这种变化。

In particular, if ColumnID is "just a normal field" then any references to it will be resolved as a field - so if you compile an assembly which refers to the field, then change the value and rebuild the assembly containing PersonRepository, the referring assembly will see that change.

如果你改变你的声明:

 public const string ColumnID = "ID";

那么它的是的编译时间常数EX pression。这意味着在我们的previous情况下,常量的值被烤成任何code,指的是 - 后来更改值而无需重新编译,当提到code的不会更改使用由参考code的值。

then it is a compile-time constant expression. That means in our previous scenario, the value of the constant is baked into any code that refers to it - and changing the value later without recompiling that referring code won't change the value used by that referring code.

有关什么算是一个恒定的前pression更多详细信息,请参见C#4语言规范的第7.19。

See section 7.19 of the C# 4 language specification for more details about what counts as a constant expression.