gpt4 book ai didi

c# - 是否可以在 C# 中使用全局方法

转载 作者:太空宇宙 更新时间:2023-11-03 17:16:53 25 4
gpt4 key购买 nike

所以我有一个静态类,假设它叫做 Worker,然后假设我在其中有一个名为 Wait(float f) 的方法,它是公开的,所以我可以像这样在任何地方访问它:

Worker.Wait(1000);

现在我想知道有什么方法可以定义某种独特的特殊的方法,所以我可以像这样简短地做:

Wait(1000);

(没有它在类里面我会用它)?

最佳答案

With C# 6 this can be done .在文件顶部,您需要添加 using static Your.Type.Name.Here;

namespace MyNamespace
{

public static class Worker
{
public static void Wait(int msec)
{
....
}
}
}

//In another file

using static MyNamespace.Worker;

public class Foo
{
public void Bar()
{
Wait(500); //Is the same as calling "MyNamespace.Worker.Wait(500);" here
}
}

关于c# - 是否可以在 C# 中使用全局方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40515179/

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