Can I add extension methods to an existing static class?

前端 未结 15 1728
慢半拍i
慢半拍i 2020-11-22 07:23

I\'m a fan of extension methods in C#, but haven\'t had any success adding an extension method to a static class, such as Console.

For example, if I want to add an e

15条回答
  •  一向
    一向 (楼主)
    2020-11-22 07:36

    As for extension methods, extension methods themselves are static; but they are invoked as if they are instance methods. Since a static class is not instantiable, you would never have an instance of the class to invoke an extension method from. For this reason the compiler does not allow extension methods to be defined for static classes.

    Mr. Obnoxious wrote: "As any advanced .NET developer knows, new T() is slow because it generates a call to System.Activator which uses reflection to get the default constructor before calling it".

    New() is compiled to the IL "newobj" instruction if the type is known at compile time. Newobj takes a constructor for direct invocation. Calls to System.Activator.CreateInstance() compile to the IL "call" instruction to invoke System.Activator.CreateInstance(). New() when used against generic types will result in a call to System.Activator.CreateInstance(). The post by Mr. Obnoxious was unclear on this point... and well, obnoxious.

    This code:

    System.Collections.ArrayList _al = new System.Collections.ArrayList();
    System.Collections.ArrayList _al2 = (System.Collections.ArrayList)System.Activator.CreateInstance(typeof(System.Collections.ArrayList));
    

    produces this IL:

      .locals init ([0] class [mscorlib]System.Collections.ArrayList _al,
               [1] class [mscorlib]System.Collections.ArrayList _al2)
      IL_0001:  newobj     instance void [mscorlib]System.Collections.ArrayList::.ctor()
      IL_0006:  stloc.0
      IL_0007:  ldtoken    [mscorlib]System.Collections.ArrayList
      IL_000c:  call       class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle)
      IL_0011:  call       object [mscorlib]System.Activator::CreateInstance(class [mscorlib]System.Type)
      IL_0016:  castclass  [mscorlib]System.Collections.ArrayList
      IL_001b:  stloc.1
    

提交回复
热议问题