I have a method with a signature
string GenericMethod<T>();
Usually you’d call this simply with:
var result = GenericMethod<AType>();
However, that doesn’t work for my case because AType is passed to the parent method as a Type.
There’s code below which shows where I’ve got to. Currently it errors as //ERROR HERE.
Before the code, quick explanation: TestClass implements both ITestClass and INotTestClass. This is important because the point here is, if I am passed a TestClass, I would want to invoke the method with ITestClass, not INotTestClass.
TestClass has a method that simply returns the name of the type in its generic brackets.
Ok, here’s the code in the form of a Unit test.
using System;
using NUnit.Framework;
namespace Ian.Tests
{
[TestFixture]
public class MiscTests
{
[Test]
public void WhoWeCallingTest()
{
var i = new TestClass();
i.TestGetTheType();
}
}
public class TestClass : ITestClass, INotTestClass
{
public void TestGetTheType()
{
var t1 = typeof(ITestClass);
var t2 = typeof(INotTestClass);
var t = GetType();
// so I can make a delegate normally, but no use as I don't have this info usually.
var dummyFunc = new MyDelegate<ITestClass>(GetTheType<ITestClass>);
var methodInfo = t.GetMethod("GetTheType");
var baseType = typeof(MyDelegate<>);
var delType = baseType.MakeGenericType(t1);
//ERROR HERE.
var del = Delegate.CreateDelegate(delType, this, methodInfo);
del.Method.Invoke(this, null);
}
public delegate string MyDelegate<T>();
public string GetTheType<T>()
{
return typeof(T).Name;
}
}
public interface ITestClass { }
public interface INotTestClass { }
}
You need to use MethodInfo.MakeGenericMethod to construct the appropriate method: