Skip to main content
 首页 » 编程设计

c#之C#6 "using static"特性的正确使用方法

2024年02月05日12zhenyulu

<分区>

如何以正确的方式使用 C#6 using static 特性?对于将 string.Format (CultureInfo.InvariantCulture, "Some format"); 缩短为 Format (InvariantCulture, "Some format"); 这样的情况,它看起来确实不错,但是总是这样吗?

以这个为例。你有像这样的 enum:

enum Enum { Value1, Value2 } 

然后您决定在这样的代码中使用它:

using static {Namespace}.Enum; 
// ... 
var value = Value1; 

后来您决定创建一个名为 Value1 的 class。然后你的代码 var value = Value1 会产生编译错误:

'Value1' is a type, which is not valid in the given context

或者其他情况。您有两个具有不同 static 方法的类:

class Foo { 
    public static void Method1() { } 
} 
 
class Foo2 { 
    public static void Method2() { } 
} 

然后你在第 3 个 class 中使用它

using static {Namespace}.Foo; 
using static {Namespace}.Foo2; 
// ... 
class Bar { 
    void Method() { 
        Method1(); 
        Method2(); 
    } 
} 

效果很好。但是如果你决定在 Foo class 中引入 Method2 这段代码将产生编译错误:

The call is ambiguous between the following methods or properties: 'Foo.Method2()' and 'Foo2.Method2()'

所以我的问题是什么是使用 using static 特性的正确方法?