你可以添加你喜欢调用静态方法扩展方法? [英] Can you add extension methods that you call like static methods?

查看:150
本文介绍了你可以添加你喜欢调用静态方法扩展方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据微软称,扩展方法是一种特殊的静态方法,但他们被称为好像他们是在扩展类型的实例方法。



时有没有办法添加一个扩展方法,它叫,就好像它是一个静态方法? ?还是做别的,有同样的效果。



编辑:
我指的是叫,就好像它是在扩​​展类的静态方法 。
很抱歉的模糊性。


解决方案

据微软称,扩展方法是特殊的静态方法,但他们被称为好像他们是在扩展型的实例的方法。




是的,扩展方法静态方法。它们都可以称为以正常的方式为静态方法,如在它们扩展的类型扩展实例方法,并且它们甚至可以称为上空引用扩展方法



例如:

 公共静态类扩展{
公共静态布尔IsNullOrEmpty(此字符串theString){
返回string.IsNullOrEmpty(theString);
}
}

//代码的其他地方。
字符串测试= NULL;
Console.WriteLine(test.IsNullOrEmpty()); //有效的代码。
Console.WriteLine(Extensions.IsNullOrEmpty(试验)); //有效的代码。



编辑:




有没有办法添加一个扩展方法,它叫,就好像它是一个静态方法?




你的意思是你要调用,例如,string.MyExtensionMethod()?在这种情况下,没有,有没有办法做到这一点。


According to Microsoft, "Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type".

Is there a way to add an extension method that it called as if it was a static method? Or to do something else that has the same effect?

Edit: By which I mean "called as if it was a static method on the extended class". Sorry for the ambiguity.

解决方案

According to Microsoft, "Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type".

Yes, extension methods are static methods. They can all be called in the normal way as static methods, as extension instance methods on the type they "extend", and they can even be called as extension methods on a null reference.

For example:

public static class Extensions {
    public static bool IsNullOrEmpty(this string theString) {
        return string.IsNullOrEmpty(theString);
    }
}

// Code elsewhere.
string test = null;
Console.WriteLine(test.IsNullOrEmpty()); // Valid code.
Console.WriteLine(Extensions.IsNullOrEmpty(test)); // Valid code.

Edit:

Is there a way to add an extension method that it called as if it was a static method?

Do you mean you want to call, for example, string.MyExtensionMethod()? In this case, no, there is no way to do that.

这篇关于你可以添加你喜欢调用静态方法扩展方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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