简体   繁体   English

将方法作为扩展方法调用比直接调用它需要更多的引用

[英]Calling a method as an Extension Method requires more reference than calling it directly

I have a extension method in what I will call HelperAssembly that looks similar to this: 我有一个扩展方法,我将调用HelperAssembly看起来类似于:

public static class HelperClass
{
    public static void MyHelperMethod(this SomeClass some, OtherClass other)
    {
        // This object is defined in OtherAssembly1
        ObjectFromOtherAssembly1 object1 = new ObjectFromOtherAssembly1(some);

        // This object is defined in OtherAssembly2
        ObjectFromOtherAssembly2 object2 = new ObjectFromOtherAssembly2(other);

        DoStuffWith(object1, object2);    
    }
}

I have an assembly I will call CallerAssembly that has a reference to HelperAssembly . 我有一个程序集,我将调用CallerAssembly ,它引用了HelperAssembly

My HelperAssembly has a reference to both OtherAssembly1 and OtherAssembly2 . 我的HelperAssembly引用了OtherAssembly1OtherAssembly2

SomeClass and OtherClass are both defineded in ReferenceAssembly . SomeClass和OtherClass都在ReferenceAssembly中定义 HelperAssembly and CallerAssembly have a reference to ReferenceAssembly . HelperAssemblyCallerAssembly引用了ReferenceAssembly

Everything is great when I call my method from CallerAssembly like this: 当我从CallerAssembly调用我的方法时,一切都很棒:

HelperClass.MyHelperMethod(some, other);

However, I get build errors when I call it like this (as an extension method): 但是,当我像这样调用它时(作为扩展方法),我会遇到构建错误:

some.MyHelperMethod(other);

The errors say that CallerAssembly needs to reference OtherAssembly1 and OtherAssembly2 . 错误表明CallerAssembly需要引用OtherAssembly1OtherAssembly2

I am confused. 我很困惑。 I thought that extension method syntax was just syntactical sugar, but did not actually change the way that things compiled. 我认为扩展方法语法只是语法糖,但实际上并没有改变编译方式。

I do not want to add the references that it is suggesting so I will not make the call as an Extension Method. 我不想添加它建议的引用,所以我不会将调用作为扩展方法。 But I would like to understand what the difference is. 但我想了解不同之处。

Why does calling the method directly build fine but calling it as an Extension Method fail to build? 为什么调用方法直接构建正常但调用它作为扩展方法无法构建?

Any chance that CallerAssembly targets the .NET Framework Client profile and HelperAssembly targets the "full" .NET Framework? CallerAssembly是否有可能将.NET Framework Client配置文件和HelperAssembly作为目标“完整”的.NET Framework?

I've run into problems with Extension methods (and other things) when I've done this. 当我这样做时,我遇到了Extension方法(和其他东西)的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM