【问题标题】:C# type of enclosing classC# 类型的封闭类
【发布时间】:2015-08-29 00:46:32
【问题描述】:

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

类似(this_type 是占位符):

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

显然,我可以只使用实际的类型名称,但我有几个遵循这种模式的类,并且想要一些不太容易出现复制/粘贴错误的类。

【问题讨论】:

标签: c#


【解决方案1】:

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

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

顺便说一句,当你执行这段代码试图获取托管对象的大小时,你会得到一个运行时异常。

【讨论】:

  • 我同意这个答案,应该被接受为正确的。问题是关于获取调用者的大小,而不是方法类所有者的大小......我的错:-)
【解决方案2】:

typeof(Message) 将是您在这里最接近的,但我认为您需要使用结构而不是类来执行此操作。

【讨论】:

    【解决方案3】:

    也许:

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

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

    【讨论】:

      【解决方案4】:

      对于类型的扩展方法并动态获取它而不是将其推送到只读静态变量呢?

      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();
      

      【讨论】:

        【解决方案5】:

        在短暂的谷歌搜索之后,我看到其他人使用反射来完成您在谈论的内容,但需要注意的是,它可能比仅输入 typeof(this_type) 昂贵得多。我建议您直接输入。

        Type t = MethodBase.GetCurrentMethod().DeclaringType
        

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-02-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多