简体   繁体   中英

how to change sealed class method by static class or another way?

I want to override a method of the Sealed Class from a static class .

For example:

public class MyClass
{
    public virtual void MyMethod()
    {
        Console.WriteLine("I'm MyMethod from MyClass");
    }
}

public sealed class MySealedClass : MyClass
{
    public override void MyMethod()
    {
        Console.WriteLine("I'm MyMethod from MySealedClass");
    }
}

The MyClass have a virtual method by name MyMethod .

In the sealed class this method has been override for self and i want to be written that again for another job by this static class:

public static class ClassManager
{
    public static void MyMethod(this MySealedClass msc)
    {
        Console.WriteLine("I'm MyMethod from ClassManager");
    }
}

Now, we call that static method's from Program class to run it:

class Program
{
    static void Main(string[] args)
    {
        new MySealedClass().MyMethod();
    }
}

But this result called MySealedClass methods not called my static class method's !!

I'm MyMethod from MySealedClass

Please help me, how to change sealed class method by static class or another way ?

You can't do that.Extensions methods are considered only if there is no method with that signature in your type.

You need to call your static method explicitly:

ClassManager.MyMethod(new MySealedClass());

It isn't possible. From MSDN :

An extension method with the same name and signature as an interface or class method will never be called . At compile time, extension methods always have lower priority than instance methods defined in the type itself. In other words, if a type has a method named Process(int i), and you have an extension method with the same signature, the compiler will always bind to the instance method.

From the C# spec:

The preceding rules (the set of rules specified in the spec) mean that instance methods take precedence over extension methods , that extension methods available in inner namespace declarations take precedence over extension methods available in outer namespace declarations, and that extension methods declared directly in a namespace take precedence over extension methods imported into that same namespace with a using namespace directive.

You'll have to invoke the method via your static class, and not as an extension method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM