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.
我相信这个问题与这个问题相似:为什么不根据其对象的运行时类型选择此方法?,而是用于 .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.
这篇关于基于运行时类型而不是编译时类型的调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:基于运行时类型而不是编译时类型的调用方法
基础教程推荐
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
