基于编译时类型的运行时类型的调用方法 [英] Calling method based on run-time type insead of compile-time type
问题描述
在应用程序中,我需要.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.
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.
推荐答案
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屋!