Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 我可以从嵌套结构中引用常量字段而不引用包含的类吗?_C# - Fatal编程技术网

C# 我可以从嵌套结构中引用常量字段而不引用包含的类吗?

C# 我可以从嵌套结构中引用常量字段而不引用包含的类吗?,c#,C#,考虑以下情况 public class SomethingWithAReallyReallyAnnoyinglyLongName{ public struct Names { public const string SomeConstant = "Hello"; public const string SomeOtherConstant = "World"; } } 有没有一种方法可以在Something With AreallyReal

考虑以下情况

public class SomethingWithAReallyReallyAnnoyinglyLongName{
    public struct Names
    {
        public const string SomeConstant = "Hello";
        public const string SomeOtherConstant = "World";
    }
}
有没有一种方法可以在
Something With AreallyReallyanyinglyLongName.Names.Something常量
上下文之外引用
Something With AreallyReallyanyinglyLongName
而不必引用
Something With AreallylylyanyinglyLongName

// 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结构的任何内容(将其设置为类,将常量更改为非常量,等等)


有什么想法吗?

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

using SwarralnNames = SomethingWithAReallyReallyAnnoyingLongName.Names;
然后您可以键入
SwarralnNames.SomeConstant


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

您是否可以将
名称
类型移到
以外的其他名称中,并使用AreallyReallyanylyLongName
?出于这个原因,我真的很讨厌嵌套类型。如果不是,那么该解决方案如何:

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
中相同的常量值,而
No-
const
字段实际上是
static
,并且必须由类名限定。是生成整个类还是仅生成名称?@DStanley生成整个类。但是我可以调整代码域(我正在做的就是添加名称),你可以使用别名,比如使用Shortcut=SomethingWithAReallyReallyAnnoyinglyLongName.Names;然后就是捷径。我读到的一些ConstantLast,C#6会有类似的东西,但我不知道这是否最终确定,或者它是否适用于非静态类。Maybee可以提供帮助。这实际上可能有效。。。没有意识到可以将其用于类/结构…NamesConstants是特定于SomethingWithAReallyReallyAnnoyinglyLongName的。还有其他类似的类将具有类似的NamesConstants,因此此解决方案不会真正起作用。好吧,它肯定会起作用,您只需要为这些类中的每一个都有一个不同的
NamesConstants
结构(每个类都有不同的名称)。这可能比使用
别名策略的
扩展得更好,但这取决于访问这些值的位置以及这些类的数量。我有大约100多个长名称的类,每个类都包含一个名为name的结构。NamesConstants每100个类必须是唯一的,所以它确实不能很好地工作。