gpt4 book ai didi

c# - .Net 在编译时将类常量设置为其命名空间

转载 作者:太空宇宙 更新时间:2023-11-03 19:56:44 25 4
gpt4 key购买 nike

有没有一种很好的方法可以将常量设置为类命名空间的常量?

namespace ACMECompany.ACMEApp.Services
{
public class MyService
{
private const string WhatWeDo = "ACMECompany.ACMEApp.Services";
private const string WouldBeNice = typeof(MyService).Namespace;

...

}
}

这样,如果类被移动到另一个命名空间,我们就不需要担心这些常量。

更多信息该常量仅真正用于日志记录 - 它被传递给某些日志方法。这些都是遗留代码,因此短期内不会更改。我知道运行时获取此信息的方法,例如 This Question

我们正在使用 .NET 4,但很快就会升级到 .NET 4.5。

最佳答案

您不会设置具有非常量值的常量变量。这是可以理解的,不是吗?

顺便说一句,C# 有 readonly关键字,一旦对象构造时间结束,将任何类字段像常量一样工作。它们可以是也可以不是静态的:

public class MyService
{
static MyService()
{
WouldBeNice = typeof(MyService).Namespace;
}

private static readonly string WouldBeNice;
}

或者...

public class MyService
{
private static readonly string WouldBeNice = typeof(MyService).Namespace;
}

此外,您可以使用只读属性实现相同的行为:

// Prior to C# 6...
public class MyService
{
private static string WouldBeNice { get { return typeof(MyService).Namespace; } }
}

// Now using C# 6...
public class MyService
{
private static string WouldBeNice => typeof(MyService).Namespace;
}

// Also using C# 6...
public class MyService
{
// This can be even better, because this sets the namespace
// to the auto-generated backing class field created during compile-time
private static string WouldBeNice { get; } = typeof(MyService).Namespace;
}

关于c# - .Net 在编译时将类常量设置为其命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32860819/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com