简体   繁体   English

在C#中调用共享相同方法名称的任何类

[英]Call any class sharing the same method name in C#

I have a significant number of classes which share the same method name, but don not share a common base/interface. 我有很多类,它们共享相同的方法名称,但是不共享通用的基类/接口。 I cannot touch these classes, however, can I call the method irrespective of the defining class? 我无法触摸这些类,但是,无论定义类如何,都可以调用该方法吗?

Eg: 例如:

Namespace n1: class A { void M1(n1.CustObj ob1){} }
Namespace n2: class B { void M1(n2.CustObj ob1){} }

Would it be possible to abstract from these common methods/parameters, like so? 是否可以像这样从这些通用方法/参数中抽象出来?

method(Object obj)
{
    obj.M1(new CustObj() { 
        x = 3; 
    }); // CustObj can either belong to n1 or n2
}

You could use either the dynamic keyword or reflection. 您可以使用dynamic关键字或反射。

Of the two, I prefer dynamic . 在这两者中,我更喜欢dynamic However, since your constructor argument is also a different type you'd need to do something like this: 但是,由于构造函数参数也是不同的类型,因此您需要执行以下操作:

void method(dynamic obj, dynamic arg)
{
    arg.x = 3;
    obj.M1(arg);
}

I understand it's unlikely that your code is set up to do this but you haven't shown much of how your method is used. 我知道您的代码不太可能设置为执行此操作,但是您并未展示如何使用方法。 And in the end, this might be the best you can do if you're unable to modify the existing classes. 最后,如果您无法修改现有的类,那么这可能是最好的选择。

You have a number of classes, each of which has a method, with the same name, but with a different signature. 您有许多类,每个类都有一个方法,名称相同,但签名不同。 The identical method names are a red herring here therefore as they are different methods. 相同的方法名称在这里是一个红色的鲱鱼,因此它们是不同的方法。

This therefore rules out using dynamic or reflection to provide a single method that can handle all of them, unless you then hard-code tests for each type within the one method, or take Jonathan Wood's approach of passing in an existing instance of CustObj via a dynamic parameter too. 因此,这排除了使用dynamic或反射提供单个方法的能力,该方法可以处理所有方法,除非您随后在一种方法中对每种类型进行硬编码测试,或者采用Jonathan Wood的方法通过一个方法传入现有的CustObj实例。 dynamic参数。

One solution might be to create extension methods for each type: 一种解决方案是为每种类型创建扩展方法:

public void Method(this A obj)
{
    obj.M1(new n1.CustObj()
    {
        x = 3
    }); 
}

public void Method(this B obj)
{
    obj.M1(new n2.CustObj()
    {
        x = 3
    }); 
}

and so on. 等等。 Then at least you can do someObj.Method(); 然后至少您可以执行someObj.Method(); on A , B and so forth. AB等上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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