gpt4 book ai didi

c# - 是否可以像在 VB.NET 中一样在 C# 中导入静态类?

转载 作者:太空狗 更新时间:2023-10-29 22:04:19 25 4
gpt4 key购买 nike

有没有办法在 C# 中“导入”静态类,例如 System.Math

我已经包含了一个比较。

Imports System.Math

Module Module1

Sub Main()
Dim x As Double = Cos(3.14) ''This works
End Sub

End Module

对比

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
}
}
}

最佳答案

更新:自 C# 6 起,the answer is now YES .


不可以,在 C# 中你只能导入命名空间,不能导入类。

但是,您可以给它一个更短的别名:

using M = System.Math;

现在您可以使用别名代替类名:

double y = M.Cos(3.14);

不过,请谨慎使用它。大多数情况下,代码使用描述性名称(如 Math)比神秘的 M 更具可读性。


另一个用途是从命名空间导入单个类,例如避免类名之间的冲突:

using StringBuilder = System.Text.StringBuilder;

现在只有 System.Text 命名空间中的 StringBuilder 类可以直接使用。

关于c# - 是否可以像在 VB.NET 中一样在 C# 中导入静态类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3895280/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com