.NET3.0 .NET3.5 扩展方法的介绍与使用

今天在看到有人提出方法中用过this的问题, 然后感觉自己也需要在这里作个记录. 顺便提一下其用法与细节,注意:在2.0下面使用会出现引用错误.因为这个是3.0后的产物

扩展方法的作用:

可以直接对.netFrame类库进行扩展,减少代码量.

使用时应注意的问题:
1、所在类的类名在用做扩展方法的时候无效
2、扩展方法必须是在静态类中的静态方法,静态方法的格式有特殊要求
3、扩展方法也可以当作普通的静态方法使用

当我们看到有“小标箭头”的方法就是扩展方法了,请输入下面代码,然后他细看一下,方法与扩展方法的图标.

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace Csharp.Test
{
    
public class Program
    {
        
public static void Main(string[] args)
        {
            
//代码调用
            Student student = new Student { Name = "BBB", Age = 20 };
            Console.WriteLine(student.IsValue(
"BBB"));
            
//输出true
            Console.WriteLine(student.TrueName("BBB"));
            
//输出true
            Console.ReadLine();
        }

    }
    
public class Student
    {
        
public string Name { getset; }

        
public int Age { getset; }
    }

    
public static class test
    {
        
public static bool IsValue(this Student student, object o)
        {
            
if (student.Name == o)
            {
                
return true;
            }
            
return false;
        }
    }

    
public static class EooPoo
    {
        
public static string TrueName(this Student student, object o)
        {
            
if (student.Name == o)
            {
                
return student.Name = "AAA";
            }
            
else
            {
                
return student.Name;
            }
        }
    }

    
}

其实按上面的意思,最简单的一句话就是,类的方法可以扩展在别的类上面通过参数this来做扩展方法.

原文地址:https://www.cnblogs.com/whtydn/p/1585878.html