是否有某种方法可以静态指定封闭类声明的类型?如果我有一个实例,我显然可以使用 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/