基于运行时类型而不是编译时类型的调用方法 [英] Calling method based on run-time type insead of compile-time type

查看:27
本文介绍了基于运行时类型而不是编译时类型的调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在应用程序中,我需要 .NET 根据运行时类型而不是编译时类型调用方法.

In an application, I need .NET to call a method based on its run-time type instead of its compile-time type.

简化示例:

    class A { }

    class B : A { }

    static void Main(string[] args)
    {
        A b = new B();
        Print(b);
    }

    static void Print(A a)
    {
        Console.WriteLine("Called from A");
    }

    static void Print(B b)
    {
        Console.WriteLine("Called from B");
    }

上面的代码实际上会打印Called from A,但我需要它是Called from B.

The above code will actually print Called from A, but I need it to be Called from B.

这按预期工作:

static void Print(A a)
{
    var b = a as B;
    if (b != null)
       return Print(b);
    else
       Console.WriteLine("Called from A");
}

但为了可维护性,这是不可取的.

But for maintainability's sake, it is not desirable.

我相信这个问题与这个问题相似:为什么不根据其对象的运行时类型选择此方法?,而是用于 .NET 而不是 Java.

I believe this question is similar to this one: Why isn't this method chosen based on the runtime-type of its object?, but for .NET instead of Java.

推荐答案

如果您使用 .NET 4 或更高版本,最简单的方法是使用 动态类型:

The simplest approach if you're using .NET 4 or higher is to use dynamic typing:

dynamic b = new B();
Print(b);

几乎所有使用 dynamic 类型值的表达式都将被动态调用,mini-C# 编译器"在执行时应用与编译时相同的规则,但是使用这些动态值的 实际 执行时间类型.(尽管类型在编译时静态已知的表达式仍将被视为具有这些类型 - 它不会使关于重载解析的所有内容都变成动态的.)

Almost all expressions using a value of type dynamic will be invoked dynamically, with a "mini-C# compiler" applying the same rules at execution time as it would have done at compile-time, but using the actual execution-time type of those dynamic values. (Expressions whose types are known statically at compile-time will still be regarded as having those types though - it doesn't make everything about overload resolution into dynamic.)

如果您不使用 .NET 4,那就更难了 - 您可以使用反射,或者对选项进行硬编码,这都不好玩.

If you're not using .NET 4, it's somewhat harder - you could either use reflection, or hard-code the options, neither of which is fun.

这篇关于基于运行时类型而不是编译时类型的调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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