C#中的扩展方法
什么是扩展方法?
Extension method means Class name and method name are having with Static Key word.
使用“this”关键字的扩展方法,第一个签名应该是提及识别地址,这个类型必须与like相同,
公共静态字符串 Meth(这个字符串 i,int j)
和
字符串 res = "ae".Meth(num);
粗体部分为识别地址。命名空间应该相同。
为什么我们需要扩展?
我们在很多地方都使用了相同的功能,后来找不到我们在这里使用的原因。为此使用地址标识。静态意味着单个实例。这只能访问静态成员函数。甚至在静态类中没有静态类方法如何访问?例如:参见“Sal”方法中的抛出错误,
静态类 Emp
{
公共 int Sal(int i,int j)
{
返回 i * j;
}
}
仅访问静态成员。还有
enter image description here
以下代码我们无法在静态类中为非静态类创建对象。那么如何将非静态方法访问到静态类中。为此,我们遵循不继承的扩展方法。
例如,在这里使用扩展方法添加或什至功能,
使用系统。文字;
使用 System.Threading.Tasks;
命名空间扩展方法
{
静态类程序
{
public static string Meth (this string i,int j)
{
if (j % 2 == 0)
{
return "Even";
}
else
{
return "ODD";
}
}
}
class program2
{
static void Main (string [] args)
{
Console. WriteLine ("Enter Integer");
int num = Convert.ToInt32(Console.ReadLine());
string res = "ae".Meth(num);
Console. WriteLine(res);
Console.ReadLine();
}
}
结果:
enter image description here