成员访问调用不编译,但静态调用

kus*_*men 10 c# syntax-checking visual-studio

所以今天我在尝试建立公司解决方案时遇到了一些有趣的问题,我想问你们,你们知道为什么会这样吗?我被告知它可能来自我的机器/视觉工作室,因为其他人没有同样的问题.

所以我们在项目中有一个方法A:

private static string RpcRoutingKeyNamingConvention(Type messageType, ITypeNameSerializer typeNameSerializer)
{
   string queueName = typeNameSerializer.Serialize(messageType);

   return messageType.GetAttribute<GlobalRPCRequest>() != null || AvailabilityZone == null
        ? queueName
        : queueName + "_" + AvailabilityZone;
}
Run Code Online (Sandbox Code Playgroud)

在哪里GetAttribute<GlobalRPCRequest>()定义public static class ReflectionHelpers

 public static TAttribute GetAttribute<TAttribute>(this Type type) where TAttribute : Attribute;
Run Code Online (Sandbox Code Playgroud)

然后我们有项目B有方法:

public static string GetAttribute(this XElement node, string name)
{
   var xa = node.Attribute(name);
   return xa != null ? xa.Value : "";
}
Run Code Online (Sandbox Code Playgroud)

我必须指出,我们B在项目中引用了项目A.现在发生的是,当我尝试构建时,我得到编译错误:

错误966"System.Xml.Linq.XElement"类型在未引用的程序集中定义.您必须添加对程序集'System.Xml.Linq,Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089'的引用.D:\ Repositories\website\website\submodules\core\src\A\Extensions\Extensions.cs 37 13 A

发生的事情是编译器认为我实际上正在使用GetAttribute项目B中的方法(在我看来!).为什么会这样?因为当我尝试导航到GetAttributeVS 时,我会找到正确的方法(正确的方法ReflectionHelpers).可能是因为反思?注意:我通过静态调用方法或在我的项目中添加对System.Xml.Linq的引用来修复此问题A,但我很好奇VS /语法检查功能的奇怪行为.

zok*_*kan 0

我猜正在发生这种情况:
- B 引用了 System.Xml.Linq
- B 的构建没有问题。
- 您在 A 中引用 B
- A 没有引用 System.Xml.Linq
- A 似乎使用了 B 中定义的函数
- 当您尝试构建项目 A 时,它会产生该错误

我对吗?

如果是这样的话,那是完全正常的。因为使用引用 (A) 的项目必须具有对其所引用的内容 (B) 所引用的内容 (System.Xml.Linq) 的引用。

像这样思考:当您尝试将 nuget 包添加到项目中时(如果它具有依赖项),nuget 也会安装它。为什么?因为这样的情况。

如果我正确理解你的答案,这是完全正常的。