【问题标题】:Can I Reference Const Fields From a Nested Struct Without Referencing the Containing Class?我可以在不引用包含类的情况下从嵌套结构中引用 const 字段吗?
【发布时间】:2015-04-09 15:57:21
【问题描述】:

考虑以下情况

public class SomethingWithAReallyReallyAnnoyinglyLongName{
    public struct Names
    {
        public const string SomeConstant = "Hello";
        public const string SomeOtherConstant = "World";
    }
}

SomethingWithAReallyReallyAnnoyinglyLongName 上下文之外时,有没有一种方法可以引用SomethingWithAReallyReallyAnnoyinglyLongName.Names.SomeConstant 而不必引用SomethingWithAReallyReallyAnnoyinglyLongName

// Won't work "Struct Name is not valid at this point."
var names = SomethingWithAReallyReallyAnnoyinglyLongName.Names;
SomeFunction(names.SomeConstant, names.SomeOtherConstant);

// Won't work "Cannot access static constant..."
var names = new SomethingWithAReallyReallyAnnoyinglyLongName.Names();
SomeFunction(names.SomeConstant, names.SomeOtherConstant);

长类名是自动生成的,所以我无法更改它,但我可能会更改 Names 结构的任何内容(使其成为一个类,将 const 更改为非 const 等)。

有什么想法吗?

【问题讨论】:

  • 否 - const 字段实际上是 static 并且必须由类名限定。生成的是整个类还是只是名称?
  • @DStanley 生成了整个类。但我可以调整 CodeDom(这是我正在做的添加名称)
  • 您可以使用别名,例如 using Shortcut = SomethingWithAReallyReallyAnnoyinglyLongName.Names;然后只是 Shortcut.SomeConstant
  • 上次我读到,C# 6 会有类似的东西,但我不知道它是否已经完成,或者它是否适用于非静态类。
  • Maybee this 可以提供帮助。

标签: c#


【解决方案1】:

好吧,在使用该类的文件中,您可以这样做:

using SwarralnNames = SomethingWithAReallyReallyAnnoyingLongName.Names;

然后你可以输入SwarralnNames.SomeConstant

不理想,因为您需要在每个需要适当“快捷方式”名称的文件中应用此 using,但如果您无法控制原始名称,它确实可以帮助清理同一文件中的多个引用。

【讨论】:

  • 这实际上可以工作......没有意识到你可以将它用于类/结构......
【解决方案2】:

你能把Names 类型移到SomethingWithAReallyReallyAnnoyinglyLongName 之外吗?出于这个原因,我真的很讨厌嵌套类型。如果没有,那么这个解决方案怎么样:

public struct NamesConstants
{ 
    public const string SomeConstant = "Hello";
    public const string SomeOtherConstant = "World";
}

public class SomethingWithAReallyReallyAnnoyinglyLongName{
    public struct Names
    {
        public const string SomeConstant = NamesConstants.SomeConstant;
        public const string SomeOtherConstant = NamesConstants.SomeOtherConstant;
    }
}

这样您可以引用NamesConstants 中的常量,而不必完全限定嵌套类型,并且嵌套类型只需使用与NamesConstants 中相同的常量值。

【讨论】:

  • NamesConstants 特定于 SomethingWithAReallyReallyAnnoyinglyLongName。还有其他类似的类会有类似的 NamesConstants,所以这个解决方案不会真正起作用。
  • 嗯,它肯定会工作,你会为这些类中的每一个拥有不同的NamesConstants 结构(显然每个类都有不同的名称)。这可能比 using 别名策略更好地扩展,但这取决于您要访问这些值的位置以及您拥有的这些类的数量。
  • 我有大约 100 多个具有长名称的类,每个类都包含一个名为 Names 的结构。 NamesConstants 每 100 个类必须是唯一的,所以它真的不能很好地工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-14
相关资源
最近更新 更多