2016-04-26 33 views
1

第一个代码示例:如何从父母和孩子扩展方法具有相同的名称

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 

那么,是不是可以做到什么,我在这里做什么? 我认为最具体的延伸将被拿起,但显然并非如此。

+0

,为什么孩子一偶存在?? –

+3

这可能会为您澄清:https://blogs.msdn.microsoft.com/ericlippert/2009/12/10/constraints-are-not-part-of-the-signature/ – NWard

+1

[This](http:/ /stackoverflow.com/questions/31788804/how-to-hide-extension-methods-from-derived-classes?rq=1)似乎相关。 –

回答

2

您可以删除泛型参数:

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); 
+0

这解决了我的问题,但是可以从子项调用父扩展方法吗? –

+0

@YannThibodeau在子扩展的正文中,在适当的地方添加'ParentExtension.DoSomething(element);'。 – Xiaoy312

+0

感谢您填补我缺乏的知识,欢呼。完美工作。你不可以这样称呼扩展方法吗? –

相关问题