C# 常数与函数<;字符串>;

C# 常数与函数<;字符串>;,c#,C#,在类中使用const或Func有什么优点或区别 public sealed class Constants { private Constants() {} public const string SOME_STRING = "Some String"; public static Func<string> SomeString = () => "Some String"; } Debug.WriteLine(Constants.SOME_STRING); De

在类中使用const或Func有什么优点或区别

public sealed class Constants {
  private Constants() {}
  public const string SOME_STRING = "Some String";
  public static Func<string> SomeString = () => "Some String";
}


Debug.WriteLine(Constants.SOME_STRING);
Debug.WriteLine(Constants.SomeString());
公共密封类常量{
私有常量(){}
public const string SOME_string=“SOME string”;
公共静态Func SomeString=()=>“Some String”;
}
Debug.WriteLine(常量.一些字符串);
Debug.WriteLine(Constants.SomeString());

编译时,常量。某些字符串将被其实际值“SOME STRING”替换,编译将继续,就像使用了文字一样


对SomeString()的调用仍然会导致对静态方法的堆栈调用。

不需要计算该常量,因此会稍微提高性能。如果确定此字符串永远不需要更改,请使用常量

如果您认为该值可能需要在将来的某个时候通过某种逻辑生成,或者它可能会从一个产品版本更改到下一个产品版本,请尝试使用属性。它为您提供了与
Func
相同的灵活性,但允许您使用不暗示可能产生其他影响的语法

public string SomeString {get {return "Some String";}}

常量在代码中引用时由其值替代,因此速度更快。生成一个Func并在代码中调用它将增加函数调用并降低性能

对于所显示的内容,请使用
常量
。你的意图很清楚


Func
只是一个函数,表示为一个对象。您似乎不需要函数,那么为什么要使用函数呢?直接访问更容易理解,更多的人会期待它。如果我看到Func的这种用法,我肯定会加倍努力。

我甚至从未想过用
Func
作为
const
的替代品。我认为使用r/o属性将是一种有效的替代方法。不要忘记
只读
值。如果您想要接近常量的值,但可以在以后更改它,使用
public static readonly
而不是funcy。它内联的可能性不是很高吗?认为const是最明显的意图,另一种方式让我感觉就像在你屁股上做牙科手术。