有什么方法重载在C#扩展方法? [英] Is there any way to overload extension methods in C#?

查看:151
本文介绍了有什么方法重载在C#扩展方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的模型模式:

public abstract class PARENTCLASS {...}
public class CHILD_A_CLASS : PARENTCLASS{...}
public static class EXTENSION{
  public static METHOD(this PARENTCLASS parent){...}
  public static METHOD(this CHILD_A_CLASS child) {...}
}

喜欢的东西上面,当然会有更多的孩子(和孙子)班但我只是把其中的一个。问题是,当我打电话类似下面的扩展方法:

Something like above, of course there will be more child (and grandchild) classes but I just put one of them. The problem is, when I called the extension method like the following:

PARENTCLASS cc = new CHILD_A_CLASS();
cc.METHOD();



这将执行父扩展方法,而不是我的预期CHILD扩展方法。任何人对如何实现这个想法?
(我不考虑把方法本身到类,让它做继承,因为我想保持模型类的清洁和其他逻辑距离)。

It will execute the PARENT Extension Method instead of my-expected CHILD extension method. Anyone have idea on how to implement this? (I'm not considering putting the METHOD itself into the class and let it do inheritance because I want to keep the model class clean and away from other logic).

推荐答案

这当然是可能的超载扩展方法。你的代码是究竟是如何做到这一点的例子。

It is certainly possible to overload extension methods. Your code is an example of exactly how to do so.

您似乎什么虽然想是能够替换扩展以这样的方式,对象的运行时类型决定了扩展方法方法调用。就像在一个类中定义一个虚方法。有这样的功能没有具体的语言语法的支持。

What you appear to want though is the ability to override extension methods in such a way that the runtime type of the object will determine the extension method call. Much like defining a virtual method on a class. There is no specific language syntax support for such a feature.

如果这是你真正重要的是,它是可能的手工实现该功能。这需要一点蛮力,但它会完成这项工作。例如...

If this is really important to you though, it's possible to hand implement the feature. It requires a bit of brute force but it will get the job done. For example ...

public static class Extension {
  public static void Method(this ParentClass p) { 
    var c = p as ChildAClass;
    if ( c != null ) {
      Method(c);
    } else {
      // Do parentclass action
    }
  }
  public static void Method(this ChildAClass c) {
    ...
  }
}

这篇关于有什么方法重载在C#扩展方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆