封闭类的C#类型

时间:2015-08-28 15:46:59

标签: c#

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

类似的东西(this_type是占位符):

RewriteEngine On
RewriteRule ^search/profileview/(.*).html?$ search/profileview.php?storeid=$1&store=$2 [QSA,NC,L]

显然,我可以使用实际的类型名称,但是我有几个遵循这种模式的类,并希望减少复制/粘贴错误。

5 个答案:

答案 0 :(得分:3)

您可以使用MethodBase.GetCurrentMethod().DeclaringType,但typeof(Message)可能是更清洁的方式

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

顺便说一下,当你试图获得托管对象的大小时,你会得到一个运行时异常。

答案 1 :(得分:1)

也许:

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

这样,' Message'也可以是静态的。

答案 2 :(得分:1)

typeof(消息)将是您最接近的地方,但我认为您需要使用结构而不是类来执行此操作。

答案 3 :(得分:0)

如何对类型的扩展方法进行动态获取而不是将其推送到只读静态变量?

public static class Extensions
{
   public static int SizeOfType(this System.Type tp) {
      return Marshal.SizeOf(tp);
   }

  public static int SizeOfObjectType(this object obj) {
      return obj.GetType().SizeOfType();
   }

}

// calling it from a method, 2 ways
var size1 = this.GetType().SizeOfType();
var size2 = this.SizeOfObjectType();
var size3 = typeof(string).SizeOfType();
var size4 = "what is my type size".SizeOfObjectType();

答案 4 :(得分:0)

经过短暂的谷歌搜索后,我发现其他人使用反射来完成你所说的内容,但是需要注意的是,这可能比输入typeof(this_type)要昂贵得多。我很快就会建议你输入它。

Type t = MethodBase.GetCurrentMethod().DeclaringType

.NET: Determine the type of “this” class in its static method