"this Type type"用作方法参数



我在这里找到了这段代码。我知道它的基础知识,但是方法参数中的"此类型类型"有什么作用,请 sombody 解释一下吗?

public static bool InheritsFrom(this Type type, Type baseType)
    {
    // null does not have base type
    if (type == null)
    {
        return false;
    }
    // only interface can have null base type
    if (baseType == null)
    {
        return type.IsInterface;
    }
    // check implemented interfaces
    if (baseType.IsInterface)
    {
        return type.GetInterfaces().Contains(baseType);
    }
    // check all base types
    var currentType = type;
    while (currentType != null)
    {
        if (currentType.BaseType == baseType)
        {
            return true;
        }
        currentType = currentType.BaseType;
    }
        return false;
}

它用于扩展方法,在C#中有一个概念称为扩展方法,该语法用于扩展方法

什么是外出方法?

方法

允许程序员将方法"添加"到现有类型,而无需创建新的派生类型、重新编译或修改原始类型。方法是静态方法,它们被调用,就好像它们是扩展类型的实例方法一样。

例:

public static class Utilities
{
    public static string encryptString(this string str)
    {
           System.Security.Cryptography.MD5CryptoServiceProvider x = new      System.Security.Cryptography.MD5CryptoServiceProvider();
           byte[] data = System.Text.Encoding.ASCII.GetBytes(str);
           data = x.ComputeHash(data);
           return System.Text.Encoding.ASCII.GetString(data);
     }
}

这将扩展string类型entryptString并在string类型上添加方法。

查看此处了解更多信息:扩展方法

最新更新