C# 中是否可以像 VB.NET 中那样导入静态类?
有没有办法在 C# 中“导入”静态类,例如 System.Math?
我已经做了比较。
Imports System.Math
Module Module1
Sub Main()
Dim x As Double = Cos(3.14) ''This works
End Sub
End Module
VS
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Math; //Cannot import a class like a namespace
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
double x = Math.Cos(3.14);
double y = Cos(3.14); //Cos does not exist in current context
}
}
}
Is there a way to "Import" a static class in C# such as System.Math?
I have included a comparison.
Imports System.Math
Module Module1
Sub Main()
Dim x As Double = Cos(3.14) ''This works
End Sub
End Module
Vs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Math; //Cannot import a class like a namespace
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
double x = Math.Cos(3.14);
double y = Cos(3.14); //Cos does not exist in current context
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
更新:从 C# 6 开始,答案现在是“是”。
不可以,在 C# 中您只能导入命名空间,而不能导入类。
但是,您可以给它一个更短的别名:
现在您可以使用别名而不是类名:
但要小心如何使用它。大多数时候,使用像
Math
这样的描述性名称而不是神秘的M
使代码更具可读性。这样做的另一个用途是从命名空间导入单个类,例如避免类名之间的冲突:
现在只有来自
System.Text
命名空间的StringBuilder
类可以直接可用的。UPDATE: As of C# 6, the answer is now YES.
No, in C# you can only import namespaces, not classes.
However, you can give it a shorter alias:
Now you can use the alias instead of the class name:
Be careful how you use it, though. Most of the time the code is more readable with a descriptive name like
Math
rather than a crypticM
.Another use for this is to import a single class from a namespace, for example to avoid conflicts between class names:
Now only the
StringBuilder
class from theSystem.Text
namespace is directly available.从 C# 6.0 开始,此问题的更新答案是“是”,它提供了“使用静态”功能。因此,例如,
using static System.Math;
允许访问System.Math
的静态成员,而无需将来对Math
类进行限定。相关SO答案:
C# 中的数学引用可以缩短吗?
如何使用 C#6“使用静态”功能?
外部参考:
GitHub - C# 6 中的新语言功能
Intellitect - C# 6.0 中的静态 using 语句
An updated answer to this question is YES as of C# 6.0, which provides a
using static
feature. So, for instance,using static System.Math;
allows the static members ofSystem.Math
to be accessed without future qualification of theMath
class.Related SO answers:
Can Math references be shortened in C#?
How do I use the C#6 “Using static” feature?
External References:
GitHub - New Language Features in C# 6
Intellitect - Static Using Statement in C# 6.0
没有。您需要在 C# 中显式调用方法作为类的功能。
There isn't. You need to explicitly invoke methods as features of classes in C#.
我在想也许某种形式的扩展方法?当然,这可以进行调整。
I was thinking maybe some form of extension methods? This could be tweaked of course.
从 C# 版本 6 开始,可以通过以下语法导入静态类。
Starting with C# version 6, static classes can be imported by the following syntax.