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.
这篇关于基于运行时类型而不是编译时类型的调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:基于运行时类型而不是编译时类型的调用方法


- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 输入按键事件处理程序 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- C# 中多线程网络服务器的模式 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01