C# 反射扩展法
我有一个字符串类的扩展方法C# 反射扩展法,c#,reflection,C#,Reflection,我有一个字符串类的扩展方法 public static bool Contains(this string original, string value, StringComparison comparisionType) { return original.IndexOf(value, comparisionType) >= 0; } 但不可能通过反射得到方法 IEnumerable<MethodInfo> foundMethods = from q in typeo
public static bool Contains(this string original, string value, StringComparison comparisionType)
{
return original.IndexOf(value, comparisionType) >= 0;
}
但不可能通过反射得到方法
IEnumerable<MethodInfo> foundMethods = from q in typeof(string).GetMethods()
where q.Name == "Contains"
select q;
IEnumerable foundMethods=来自typeof(string.GetMethods()中的q
其中q.Name==“包含”
选择q;
foundMethods仅获取Contains(string)方法为什么?其他Contains方法在哪里?它不是
String
类中声明的方法,因此GetMethods
无法看到它。扩展方法是否在范围内取决于声明它的命名空间是否被导入,而反射对此一无所知。请记住,扩展只是静态方法,使用语法糖使其看起来像实例方法。它不是在字符串类中声明的方法,因此GetMethods
无法看到它。扩展方法是否在范围内取决于声明它的命名空间是否被导入,而反射对此一无所知。请记住,扩展只是静态方法,语法上的糖分使它看起来像是实例方法。您不能使用问题中列出的简单反射方法来查找扩展方法
您必须查看类和方法的,并验证第一个参数类型是否为string。由于扩展方法可以在任何程序集中定义,因此您必须对感兴趣的程序集执行此操作您不能使用问题中列出的简单反射方法来查找扩展方法
您必须查看类和方法的,并验证第一个参数类型是否为string。由于扩展方法可以在任何程序集中定义,因此您必须为感兴趣的程序集执行此操作您的Contains方法不在String类中,因此,您无法获得typeof(String).GetMethods()的Contains方法
要获得所需,可以使用代码
public partial String
{
public static bool Contains(this string original, string value, StringComparison comparisionType)
{
return original.IndexOf(value, comparisionType) >= 0;
}
}
但代码有一个问题,字符串类不能是静态的,所以不能使用此参数
所以您应该在任何静态类中定义这个Contains方法
您可以使用以下代码获得:
public static StringDemo
{
public static bool Contains(this string original, string value, StringComparison comparisionType)
{
return original.IndexOf(value, comparisionType) >= 0;
}
}
IEnumerable<MethodInfo> foundMethods = from q in typeof(StringDemo).GetMethods()
where q.Name == "Contains"
select q;
publicstaticstringdemo
{
公共静态bool包含(此字符串原始、字符串值、StringComparison ComparisonType)
{
返回original.IndexOf(value,comparisontype)>=0;
}
}
IEnumerable foundMethods=来自typeof(StringDemo).GetMethods()中的q
其中q.Name==“包含”
选择q;
您的Contains方法不在String类中,因此,无法获取typeof(String).GetMethods()的Contains方法
要获得所需,可以使用代码
public partial String
{
public static bool Contains(this string original, string value, StringComparison comparisionType)
{
return original.IndexOf(value, comparisionType) >= 0;
}
}
但代码有一个问题,字符串类不能是静态的,所以不能使用此参数
所以您应该在任何静态类中定义这个Contains方法
您可以使用以下代码获得:
public static StringDemo
{
public static bool Contains(this string original, string value, StringComparison comparisionType)
{
return original.IndexOf(value, comparisionType) >= 0;
}
}
IEnumerable<MethodInfo> foundMethods = from q in typeof(StringDemo).GetMethods()
where q.Name == "Contains"
select q;
publicstaticstringdemo
{
公共静态bool包含(此字符串原始、字符串值、StringComparison ComparisonType)
{
返回original.IndexOf(value,comparisontype)>=0;
}
}
IEnumerable foundMethods=来自typeof(StringDemo).GetMethods()中的q
其中q.Name==“包含”
选择q;