gpt4 book ai didi

c# - 为什么 C# 编译器可以 "see"静态属性,而不是实例方法,在未引用的 DLL 中的类?

转载 作者:可可西里 更新时间:2023-11-01 08:28:28 25 4
gpt4 key购买 nike

我的问题的前提,用简单的英语:

  • 名为 Foo 的库依赖于名为 Bar 的库
  • Foo 中的类扩展了 Bar 中的类
  • Foo 定义简单传递给 Bar 的属性/方法
  • 应用程序 FooBar仅依赖于 Foo

考虑以下示例:

class Program
{
static void Main(string[] args)
{
Foo foo = Foo.Instance;

int id = foo.Id; // Compiler is happy
foo.DoWorkOnBar(); // Compiler is not happy
}
}

Foo定义如下

public class Foo : Bar
{
public new static Foo Instance { get => (Foo)Bar.Instance; }

public new int Id { get => Bar.Id; }

public void DoWorkOnBar()
{
Instance.DoWork();
}
}

Bar定义如下

public class Bar
{
public static Bar Instance { get => new Bar(); }

public static int Id { get => 5; }

public void DoWork() { }
}

完全难倒我的部分:

没有引用 Bar

  • FooBar 可以检索 Bar 提供的 ID(或者至少它编译)
  • FooBar 不能请求 Foo 完成最终由 Bar
  • 完成的工作

foo.DoWorkOnBar(); 相关的编译器错误是

The type 'Bar' is defined in an assembly that is not referenced. You must add a reference to assembly 'Bar, Version 1.0.0.0, Culture=Neutral, PublicKeyToken=null' .

为什么编译器中似乎存在差异?

如果没有 FooBar 添加对 Bar 的引用,我会假设这些操作都不会编译。

最佳答案

首先,请注意 Foo.IdFoo.DoWorkOnBar实现是不相关的;即使实现不访问 Bar,编译器也会以不同方式对待 foo.Idfoo.DoWorkOnBar():

// In class Foo:
public new int Id => 0;
public void DoWorkOnBar() { }

foo.Id 编译成功但 foo.DoWorkOnBar() 编译失败的原因是编译器使用不同的逻辑¹ 来查找属性和方法。

对于foo.Id,编译器首先在Foo中寻找名为Id的成员。当编译器发现 Foo 有一个名为 Id 的属性时,编译器会停止搜索并且不会去查看 Bar。编译器可以执行此优化,因为派生类中的属性会隐藏基类中具有相同名称的所有成员,因此 foo.Id 将始终引用 Foo.Id ,无论什么成员都可能在 Bar 中被命名为 Id

对于foo.DoWorkOnBar(),编译器首先在Foo中寻找名为DoWorkOnBar的成员。当编译器发现 Foo 有一个名为 DoWorkOnBar 的方法时,编译器会继续在所有基类中搜索名为 DoWorkOnBar 的方法。编译器这样做是因为(与属性不同)方法可以重载,并且编译器实现重载决议算法的方式与 C# 规范中描述的方式基本相同:

  1. 从“方法组”开始,该方法组由 Foo 及其基类 中声明的 DoWorkOnBar 的所有重载集组成。。<
  2. 将集合缩小到“候选”方法(基本上,其参数与提供的参数兼容的方法)。
  3. 删除任何被更派生类中的候选方法遮蔽的候选方法。
  4. 从剩余的候选方法中选择“最佳”。

第 1 步触发要求您添加对程序集 Bar 的引用。

C# 编译器能否以不同方式实现算法?根据 C# 规范:

The intuitive effect of the resolution rules described above is as follows: To locate the particular method invoked by a method invocation, start with the type indicated by the method invocation and proceed up the inheritance chain until at least one applicable, accessible, non-override method declaration is found. Then perform type inference and overload resolution on the set of applicable, accessible, non-override methods declared in that type and invoke the method thus selected.

所以在我看来,答案是"is":C# 编译器理论上可以看到 Foo 声明了一个适用的 DoWorkOnBar 方法,而不必费心查看 。然而,对于 Roslyn 编译器,这将涉及对编译器的成员查找和重载解析代码的重大重写——考虑到开发人员可以很容易地自行解决此错误,这样的努力可能不值得。


TL;DR — 当您调用方法时,编译器需要您引用基类程序集,因为这是编译器的实现方式。


¹ 请参阅 Microsoft.CodeAnalysis.CSharp.Binder class 的 LookupMembersInClass 方法.

² 请参阅 Microsoft.CodeAnalysis.CSharp.OverloadResolution class 的 PerformMemberOverloadResolution 方法.

关于c# - 为什么 C# 编译器可以 "see"静态属性,而不是实例方法,在未引用的 DLL 中的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51547053/

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