gpt4 book ai didi

c# - 扩展方法与父类方法行为

转载 作者:行者123 更新时间:2023-11-30 19:13:52 25 4
gpt4 key购买 nike

看下面的代码:

class A
{
public string DoSomething(string str)
{
return "A.DoSomething: " + str;
}
}

class B : A
{
}

static class BExtensions
{
public static string DoSomething(this B b, string str)
{
return "BExtensions.DoSomething: " + str;
}
}

class Program
{
static void Main(string[] args)
{
var a = new A();
var b = new B();
Console.WriteLine(a.DoSomething("test"));
Console.WriteLine(b.DoSomething("test"));

Console.ReadKey();
}
}

代码的输出是:

A.DoSomething: test

A.DoSomething: test

编译时不会发出任何警告。

我的问题是:为什么在代码编译时没有警告,以及调用 DoSomething 方法时到底发生了什么?

最佳答案

调用方法时发生的事情很简单:只是实例方法调用。由于 C# 是早期绑定(bind)的,所有方法都在编译时解析。此外,实例方法优于扩展方法,因此这就是您的扩展方法永远不会被调用的原因。

参见 this :

You can use extension methods to extend a class or interface, but not to override them. An extension method with the same name and signature as an interface or class method will never be called. At compile time, extension methods always have lower priority than instance methods defined in the type itself.

In other words, if a type has a method named Process(int i), and you have an extension method with the same signature, the compiler will always bind to the instance method. When the compiler encounters a method invocation, it first looks for a match in the type's instance methods. If no match is found, it will search for any extension methods that are defined for the type, and bind to the first extension method that it finds.

关于c# - 扩展方法与父类方法行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2199257/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com