在int上使用扩展方法 [英] using extension methods on int

查看:113
本文介绍了在int上使用扩展方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读有关扩展方法的信息,并在其中闲逛 看看它们是如何工作的,我尝试了这一点:

I'm reading about extension methods, and monkeying around with them to see how they work, and I tried this:

namespace clunk {
    public static class oog {
        public static int doubleMe(this int x) {
            return 2 * x;
        }
    }

    class Program {
        static void Main() {
            Console.WriteLine(5.doubleMe());
        }
    }
}

并按预期工作,成功地使用doubleMe方法扩展了int,打印出10.

and it worked as expected, successfully extending int with the doubleMe method, printing 10.

接下来,作为一个老C家伙,我想知道我是否可以这样做:

Next, being an old C guy, I wondered if I could do this:

namespace clunk {
    public static class BoolLikeC {
        public static bool operator true(this int i)  { return i != 0; }
        public static bool operator false(this int i) { return i == 0; }
    }

    class Program {
        static void Main() {
            if ( 7 ) {
                Console.WriteLine("7 is so true");
            }
        }
    }
}

我想,如果前者能够奏效,那么后者应该努力使之成为现实 在布尔上下文中使用的int会在int上调用extension方法,请检查是否 7不等于0,并返回true.但是相反,编译器甚至不喜欢 后面的代码,将红色的波浪线放在这两个下面,并说预期类型". 为什么不行呢?

I would think if the former would work, then the latter ought to work to make it such that an int used in a boolean context would call the extension method on int, check to see that 7 is not equal to 0, and return true. But instead, the compiler doesn't even like the later code, and puts the red squiggly lines under the two this's and says "Type expected". Why shouldn't this work?

推荐答案

非常聪明!不错的尝试,但遗憾的是,我们没有实现扩展所有内容" ,而只是实现扩展方法.

Very clever! A nice attempt, but regrettably we did not implement "extension everything", just extension methods.

我们考虑了实现扩展属性,扩展运算符,扩展事件,扩展构造函数,扩展接口的名称,但是它们中的大多数并没有足够的吸引力将其引入C#4或即将发布的C#版本中.我们已经为您提到的那种事情设计了一种语法.我们在扩展属性上走得更远.我们几乎将扩展属性添加到了C#4中,但最终没有解决.可悲的故事在这里.

We considered implementing extension properties, extension operators, extension events, extension constructors, extension interfaces, you name it, but most of them were not compelling enough to make it into C# 4 or the upcoming version of C#. We got as far as designing a syntax for the sort of thing you mention. We got rather farther on extension properties; we almost got extension properties into C# 4 but it ended up not working out. The sad story is here.

http://blogs.msdn.com/b/ericlippert/archive/2009/10/05/why-no-extension-properties.aspx

长话短说,没有这种功能,但是我们将在假设的将来语言版本中考虑使用它.

So, long story short, no such feature, but we'll consider it for hypothetical future releases of the language.

如果您确实喜欢 non-zero-means-true 的复古C约定,那么您当然可以在int上创建一个"ToBool()"扩展方法.

You can of course make a "ToBool()" extension method on int if you really do like the retro C convention that non-zero-means-true.

这篇关于在int上使用扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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