第一个代码示例:
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 :(得分: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)
将被调用,因为Child
比Parent
更具体。
或者......这看起来很丑陋并且无法实现扩展方法的目的:
// Invoke the method explicitly
ParentExtension.DoSomething(child);
ChildExtension.DoSomething(child);