Optional parameters “must be a compile-time constant”

后端 未结 8 776
面向向阳花
面向向阳花 2020-12-01 15:42

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

public partial class PersonRepository : BaseRepository
{
    public static readonly str         


        
8条回答
  •  北荒
    北荒 (楼主)
    2020-12-01 16:18

    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.

    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.

    If you change your declaration to:

     public const string ColumnID = "ID";
    

    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.

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

提交回复
热议问题