代码之家  ›  专栏  ›  技术社区  ›  RKh

在“const”声明中避免开销

c#
  •  1
  • RKh  · 技术社区  · 15 年前

    我已经宣布 常量 以这种方式:

    const string DatabaseFilePath = 
    String.Format(System.Windows.Forms.Application.StartupPath + @"\Data Files\");
    

    我担心第一个“string”和第二个“string.Format”可能会增加一些开销。如果这是真的,建议一个更好的方法来写这个。

    3 回复  |  直到 15 年前
        1
  •  5
  •   SLaks    15 年前

    您的声明是编译器错误。
    const 字段必须是 编译时 常数;它们 不能 有方法调用。

    相反,你需要 static readonly 字段。

    另外,应该使用 Path.Combine ,它将正确处理 \ .

    把它改成

    static readonly string DatabaseFilePath = Path.Combine(Application.StartupPath, @"Data Files\");
    
        2
  •  6
  •   Darin Dimitrov    15 年前

    我以这种方式宣布了一名警察:

    不,你没有。除非你使用其他语言(不是C#),否则这甚至无法编译。

    您可能是指只读字段:

    private readonly string DatabaseFilePath = 
        Path.Combine(Application.StartupPath, "Data Files");
    

    还要注意 Path.Combine 而不是string.Format。

        3
  •  0
  •   jason    15 年前

    我以这种方式宣布了一名警察:

    const string DatabaseFilePath = 
    String.Format(System.Windows.Forms.Application.StartupPath + @"\Data Files\");
    

    因为表达式不是常量,所以不会编译。您可能知道该表达式的结果是常量(即,无论调用多少次,它都是相同的 String.Format System.Windows.Form.Application.StartupPath 但是编译器不知道!此外,不可能 StartupPath 是常量,因为它的值依赖于运行时。)您要求编译器在表达式实际上是常量的情况下无法推断出这一点。

    我担心第一个“string”和第二个“string.Format”可能会增加一些开销。

    假设它确实编译了。只有当编译器能够神奇地确定要分配给的表达式时,它才能编译 DatabaseFilePath 是不变的。但如果它能做到,那么 数据库文件路径 的值已在编译时解析。因此,唯一的开销将是在编译时。在运行时不会有。

    如果这是你想要的设计,你应该这样声明

    static readonly string DatabaseFilePath =
    Path.Combine(System.Windows.Forms.Application.StartupPath, "Data Files");
    

    但你应该更进一步说

    class X {
        private readonly string databaseFilePath;
        public X(string databaseFilePath) {
            this.databaseFilePath = databaseFilePath;
        }
    }
    

    然后去别的地方

    X x = new X(
        Path.Combine(System.Windows.Forms.Application.StartupPath, "Data Files")
    );
    

    我不知道你们班的名字,我也略去了一些无关紧要的细节,但要点很清楚。