【问题标题】:How to make a class where all fields/properties are const by default?如何创建一个所有字段/属性默认为 const 的类?
【发布时间】:2012-06-06 23:22:27
【问题描述】:

可以在 C# 中创建一个所有字段和属性默认为 const 的类吗?

  • 虚构的例子 *

public class foo : const /* or readonly */ { public int baa = 3; }

【问题讨论】:

  • “默认”是什么意思?你的意思是类的类型要求所有成员都是常量吗?
  • @SteveDog,我猜他希望它们是 const 除非另有说明。
  • 默认情况下你想要 const 的原因是什么?
  • 您似乎只是希望每个属性都有一些默认值,可以在运行时更改。

标签: c# constants


【解决方案1】:

不,不是。

您可以将类设为静态,但这会强制所有成员都是静态的。

例如:

public static class Constants
{
    public const int SomeId = 123;
    public const string SomeName = "foo";

    public static readonly DateTime myDateTime = new DateTime();

    public string notConstant = "test"; //does not compile
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-04
    • 2018-01-25
    • 1970-01-01
    • 1970-01-01
    • 2021-06-10
    • 1970-01-01
    • 2013-11-21
    • 1970-01-01
    相关资源
    最近更新 更多