为什么不允许在嵌套类的扩展方法定义是什么? [英] Why not allow Extension method definition in nested class?

查看:174
本文介绍了为什么不允许在嵌套类的扩展方法定义是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我会觉得方便/逻辑写我exensions一类的嵌套类。最主要的原因是我可以简单地命名该类扩展,让它的外部命名范围,给它一个编译器一个独特的类型名称。

I would find it convenient/logical to write my exensions for a class in a nested class. The main reason is I could simply name that class Extensions and let it's outer naming scope give it a unique type name for the compiler.

什么是技术原因不允许这样的:

What is the technical reason to disallow something like:

public class Foo
{
   ObjectSet<Bar> Bars { get; set; }

   public static class Extensions
   {
      public static Bar ByName(this ObjectSet<Bar> bars, string name)
      {
         return bars.FirstOrDefault(c => c.Name == name);
      }
   }
}



而现在我要创建。一个独立自由站立类

Whereas now I have to create a separate free standing class.

更新/注:我没有想象的事实,这是一个内部类会影响的范围扩展方法的有效性。我只是想解决的实际编码问题有一个独立的名字一个单独的类。

Update/Note: I wasn't imagining that the fact it was an inner class would affect the scope of availability of the extension method. I only wanted to address the practical coding issue a separate class with a separate name.

推荐答案

这里的关键点是,<强>嵌套类可以访问外部类的私有字段

所以,下面的代码工作:

So the following code works:

public class Foo
{
    private bool _field;

    public static class Extensions
    {
        public static bool GetField(Foo foo)
        {
            return foo._field;
        }
    }
}



在这里,您明确地传递类和静态方法的一个实例被允许访问私有字段...似乎是合理的:

Here you are explicitly passing in an instance of the class, and a static method is allowed to access a private field... seems reasonable:

bool fieldValue = Foo.Extensions.GetField(new Foo());






不过,虽然扩展方法只是一个替代语法对于静态方法,它们被调用的方式非静态实例方法相同。


However, although extension methods are just an alternative syntax for static methods, they are invoked the same way as non-static instance methods.

现在如果扩展方法是在嵌套类允许,他们可以其实进入私人领域,他们会更接近于实例方法。这可能会导致一些意想不到的后果。

Now if extension methods were allowed in nested classes, they could in fact access private fields, and they would be that much closer to instance methods. This could lead to some unintended consequences.

在总结,如果被允许:

public class Foo
{
    private bool _field;

    public static class Extensions
    {
        public static bool GetField(*this* Foo foo) // not allowed, compile error.
        {
            return foo._field;
        }
    }
}



然后,你可以编写以下码,使得扩展方法表现得有点更像是一个实例方法比它应该是:

Then you could write the following code, making the extension method behave a bit more like an instance method than it should be:

var foo = new Foo();
var iGotAPrivateField = foo.GetField();

这篇关于为什么不允许在嵌套类的扩展方法定义是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆