I wrote the extension method GenericExtension
. Now I want to call the extension method Extension
. But the value of methodInfo
is always null.
public static class MyClass
{
public static void GenericExtension<T>(this Form a, string b) where T : Form
{
// code...
}
public static void Extension(this Form a, string b, Type c)
{
MethodInfo methodInfo = typeof(Form).GetMethod("GenericExtension", new[] { typeof(string) });
MethodInfo methodInfoGeneric = methodInfo.MakeGenericMethod(new[] { c });
methodInfoGeneric.Invoke(a, new object[] { a, b });
}
private static void Main(string[] args)
{
new Form().Extension("", typeof (int));
}
}
Whats wrong?
To define and call the extension methodDefine a static class to contain the extension method. The class must be visible to client code. For more information about accessibility rules, see Access Modifiers. Implement the extension method as a static method with at least the same visibility as the containing class.
The only difference between a regular static method and an extension method is that the first parameter of the extension method specifies the type that it is going to operator on, preceded by the this keyword.
Extension methods are brought into scope at the namespace level. For example, if you have multiple static classes that contain extension methods in a single namespace named Extensions , they'll all be brought into scope by the using Extensions; directive.
In C#, the extension method concept allows you to add new methods in the existing class or in the structure without modifying the source code of the original type and you do not require any kind of special permission from the original type and there is no need to re-compile the original type.
The extension method isn't attached to the type Form
, it's attached to the type MyClass
, so grab it off that type:
MethodInfo methodInfo = typeof(MyClass).GetMethod("GenericExtension",
new[] { typeof(Form), typeof(string) });
In case you have an extension method like
public static class StringExtensions
{
public static bool IsValidType<T>(this string value);
}
you can invoke it (e. g. in tests) like so:
public class StringExtensionTests
{
[Theory]
[InlineData("Text", typeof(string), true)]
[InlineData("", typeof(string), true)]
[InlineData("Text", typeof(int), false)]
[InlineData("128", typeof(int), true)]
[InlineData("0", typeof(int), true)]
public void ShouldCheckIsValidType(string value, Type type, bool expectedResult)
{
var methodInfo =
typeof(StringExtensions).GetMethod(nameof(StringExtensions.IsValidType),
new[] { typeof(string) });
var genericMethod = methodInfo.MakeGenericMethod(type);
var result = genericMethod.Invoke(null, new[] { value });
result.Should().Be(expectedResult);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With