C# “的用法;这种类型;作为方法参数
我找到了这个密码。我知道它的基本原理,但是方法参数中的“this Type”是做什么的,sombody能解释一下吗C# “的用法;这种类型;作为方法参数,c#,types,this,C#,Types,This,我找到了这个密码。我知道它的基本原理,但是方法参数中的“this 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
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#中有一个称为扩展方法的概念,即语法用于扩展方法 什么是Extesion方法? 方法允许程序员向现有类型“添加”方法,而无需创建新的派生类型、重新编译或修改原始类型。方法是静态方法,它们被调用时就像它们是扩展类型上的实例方法一样 例如:
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
类型,并在string
类型上添加了entryptString
方法
查看此处了解更多信息:这是
类型
变量的扩展方法。