Is it possible to write an extension method for an abstract class

Why I can not extend the abstract class. Is there any work to achieve this?

There are no Enum.GetNames names in silverlight. Therefore, I would like to expand it and use it in my assembly. By then I got into it.

+5
source share
2 answers

The problem is not that you cannot add an extension method to an abstract class (you can - you can add an extension method for any type) - it is that you cannot add a static method / strong> to a type with extension methods.

- , # . . , , :)

, , , .

, , Silverlight ( - )

- , - , , ( object, ):

public static class ExtraObjectStatics
{
  public static void NewStaticMethod()
  {

  }
}

public class Test
{
  public void foo()
  {
    //You can't do this - the static method doesn't reside in the type 'object'
    object.NewStaticMethod();
    //You can, of course, do this
    ExtraObjectStatics.NewStaticMethod();
  }
}

- , , , 2, ; .

( , ), Enum :

namespace MySystem
{
  public class Enum
  {
    public static string[] GetNames()
    {
      //don't actually know how you're going to implement it :)
    }
  }
}

- , , :

using System;
using MySystem;

namespace MyCode
{
  public class TestClass
  {
    public static void Test()
    {
      Enum.GetNames(); //error: ambiguous between System and MySystem
    }
  }
}

"", "MySystem" , Enum.

:

using System;

namespace MyCode
{
  using MySystem; //move using to inside the namespace
  public class TestClass
  {
    public static void Test()
    {
      //will now work, and will target the 'MySystem.Enum.GetNames()'
      //method.
      Enum.GetNames();
    }
  }
}

( ) Enum , , using .

, Enum , using MySystem;.

: System.Enum MySystem.Enum - , System.Enum.

, - Enum System.Enum - , System.Enum.

GetNames Reflector - , , ... , Silverlight.

+6
public abstract class Foo
{
  public abstract void Bar();
}

public static class FooExtensions
{
  // most useless extension method evar
  public static void CallBar(this Foo me)
  {
    me.Bar();
  }
}

, .

+4

All Articles