如何创建具有静态返回类型的扩展方法? [英] How can I create extension methods with static return type?

查看:58
本文介绍了如何创建具有静态返回类型的扩展方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为Color静态类编写一个简单的扩展方法,该方法将返回该颜色的黑白等效.
问题在于扩展方法无法返回静态类型...
那么,我该怎么做呢?请帮我.

I was trying to write a simple extension method for Color static class which return Black and White equivalent of that color.
The problem is that extention methods can't return Static types...
So, how can I do this?! please help me.

推荐答案

问题是没有方法可以返回静态类型.静态类是无状态的(或只有静态),因此只有一个实例",可以从引用该命名空间的任何代码中进行全局访问.

The problem is that NO method can return a static type. Static classes are stateless (or have only static state), and thus have only one "instance" that is globally accessible from any code referencing the namespace.

您可以返回颜色;虽然Color类本身具有静态成员,但它不是静态的,因此可以存在很多Colors实例.您也可以将扩展方法应用于颜色.如果这样做,则可以在非静态Color结构的静态成员之一上调用扩展方法:

You can return a Color; the Color class itself, though it has static members, is not static, and so many instances of Colors can exist. You can also apply an extension method to a Color. If you do this, then you can call an extension method on one of the static members of the non-static Color struct:

public static class MyColorsExtensions
{

   public static Color ToGreyScale(this Color theColor) { ... }

}

...

var greyFromBlue = Color.Blue.ToGreyScale();

这篇关于如何创建具有静态返回类型的扩展方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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