Dynamic selection of method based on runtime parameter type

TSM*_*TSM 7 c#

I've seen similar questions/answers for this posted in the past, but mine differs slightly from the others that I've seen.

Essentially, I have a common interface and several classes that implement/inherit from it. Then, in a separate class, I have methods that must act upon objects given by the interface IObject. However, each of them must be acted upon in different ways, hence why there is a separate declaration of the method for each concrete type that extends IObject.

class IObject
{
    ...
}

class ObjectType1 : IObject
{
    ...
}

class ObjectType2 : IObject
{
    ...
}

class FooBar
{
    void Foo (ObjectType1 obj);
    void Foo (ObjectType2 obj);
}
Run Code Online (Sandbox Code Playgroud)

Now, to me, one obvious solution is to take advantage of dynamic binding by placing the method Foo inside each individual class, which would automatically choose at runtime the correct Foo to execute. However, this is not an option here, because I am defining multiple models for how to act upon these objects, and I would rather encapsulate each individual model for handling objects in its own class, rather than stuff all of the models into the object classes.

我发现这篇文章展示了如何使用字典在运行时动态选择正确的方法实现.我对这种方法很好; 但是,假设我必须在每个模型中执行一次这样的调度.如果我只有IObject及其具体实现,有没有办法概括这种方法,以便我可以根据对象的运行时类型调用任何名称方法?

我知道这可能是一个不明确的问题,但我非常感谢任何帮助.

Str*_*ior 10

dynamic关键字居然真的擅长此道:

void Main()
{
    var foobar = new FooBar();
    foreach(IObject obj in new IObject[]{ new ObjectType1(), new ObjectType2()})
    {
        foobar.Foo((dynamic)obj);
    }   
    // Output:
    //  Type 1
    //  Type 2
}

class IObject
{
}

class ObjectType1 : IObject
{
}

class ObjectType2 : IObject
{
}

class FooBar
{
    public void Foo (ObjectType1 obj) {
        Console.WriteLine("Type 1");
    }
    public void Foo (ObjectType2 obj) {
        Console.WriteLine("Type 2");
    }
}
Run Code Online (Sandbox Code Playgroud)

代码非常简单,性能相当不错.