C# 封闭类的类型

标签 c#

是否有某种方法可以静态指定封闭类声明的类型?如果我有一个实例,我显然可以使用 typeof(this),但静态地我看不到办法。

类似于(其中 this_type 是占位符):

public class Message
{
   public static readonly int SizeInBytes = Marshal.SizeOf(typeof(this_type));
}

显然,我可以只使用实际的类型名称,但我有几个遵循此模式的类,并且希望有一些不易复制/粘贴错误的类。

最佳答案

您可以使用MethodBase.GetCurrentMethod().DeclaringType,但typeof(Message)可能是更干净的方法

public class  Message
{
   public static readonly int SizeInBytes = Marshal.SizeOf(MethodBase.GetCurrentMethod().DeclaringType);
}

顺便说一句,当您执行此代码时,您会遇到运行时异常,因为它试图获取托管对象的大小。

关于C# 封闭类的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32274963/

相关文章:

c# - EF System.MissingMethodException

c# - 禁用按钮时的奇怪问题

c# - 在 WPF 中使用 ICommand

c# - 微软 Visual Studio : How to exclude certain Project Folders from publishing?

c# - 全局变量未在新线程中初始化

c# - 我应该通过绑定(bind)使用 MVP 和 WPF 显示数据吗?

c# - anchor 标记在 Gridview 中不起作用

c# - 只能在创建对象时分配的类属性?

c# - 计算节点的可能坐标

c# - 如何在 SQLite 中设置自动时间戳?