C#6 "using static" 特性的正确使用方式
The right way of using C#6 "using static" feature
如何正确使用 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
功能的正确方法是什么?
我没有阅读关于该主题的任何建议。但我的意见是,您可以使用 using static
来为您提供有意义的名称。
using static Math;
var max = Max(value1, value2);
在 string.Format
的情况下,我认为 Format
的含义变得不清楚(所有类型的东西都可以格式化成任何具有某种格式的东西)。
所陈述的 "problems" 已存在于有关类型名称解析的语言的早期版本中。
此功能只是将那些 "problems" 归结为类型成员。
如何正确使用 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
功能的正确方法是什么?
我没有阅读关于该主题的任何建议。但我的意见是,您可以使用 using static
来为您提供有意义的名称。
using static Math;
var max = Max(value1, value2);
在 string.Format
的情况下,我认为 Format
的含义变得不清楚(所有类型的东西都可以格式化成任何具有某种格式的东西)。
所陈述的 "problems" 已存在于有关类型名称解析的语言的早期版本中。
此功能只是将那些 "problems" 归结为类型成员。