gpt4 book ai didi

C# 静态 "this"

转载 作者:可可西里 更新时间:2023-11-01 07:49:36 27 4
gpt4 key购买 nike

在 C# 静态方法中是否有一种方法可以引用定义该方法的类型?

在实例方法中,您可以通过以下方式确定类型:

public void Foo()
{
Type type = this.GetType();
}

在静态方法中它会是什么样子?

public static void Bar()
{
Type type = ....?
}

更新:抱歉,需要澄清:我知道 typeof(...) 功能。我正在寻找一个关键字或代码,它可以在不显式引用类名的情况下为我提供类型。

更新:除了 Developer Art 的答案完全符合我的要求,还有更简单的方法吗?

最佳答案

给你:

public static void Bar()
{
Type type = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType;
}

编辑:已更新以更正错误 - DeclaringType 是一个属性。

关于C# 静态 "this",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3889334/

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