如何使用相同的名称从 parent 和 child 扩展方法

How to extend method from parent and child with the same name

第一个代码示例:

public class Parent
{

}

public static class ParentExtension
{
    public static void DoSomething<T>(this T element) where T : Parent
    {
        ...
    }
}

public class Child : Parent
{

}
public static class ChildExtension
{
    public static void DoSomething<T>(this T element) where T : Child
    {
        ...
    }
}
//Trying to call child extension class
var child = new Child();
child.DoSomething(); //Actually calls the parent extension method even though it is a child class

那么,是否可以完成我在这里所做的事情? 我以为会选择最具体的扩展名,但事实显然并非如此。

您可以删除通用参数:

public static class ParentExtension
{
    public static void DoSomething(this Parent element)
    {
        // ...
    }
}
public static class ChildExtension
{
    public static void DoSomething(this Child element)
    {
        // ...
    }
}

注意:void ChildExtension::DoSomething(this Child element) 将被调用,因为 ChildParent 更具体。


或者...这看起来很难看并且破坏了使用扩展方法的目的:

// Invoke the method explicitly
ParentExtension.DoSomething(child);
ChildExtension.DoSomething(child);