我有一个带有签名的方法
string GenericMethod<T>();
通常你会简单地调用它:
var result = GenericMethod<AType>();
但是,这对我的情况不起作用,因为 AType
作为 Type
传递给父方法。
下面的代码显示了我必须到达的位置。目前它错误为//ERROR HERE。
在代码之前,快速解释一下:TestClass
实现了 ITestClass
和 INotTestClass
。这一点很重要,因为这里的要点是,如果向我传递了一个 TestClass
,我会希望使用 ITestClass
而不是 INotTestClass
来调用该方法。
TestClass
有一个方法,它只返回其通用括号中的类型名称。
好的,这是单元测试形式的代码。
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 { }
}
最佳答案
您需要使用 MethodInfo.MakeGenericMethod构建适当的方法:
var methodInfo = t.GetMethod("GetTheType");
var methodWithType = methodInfo.MakeGenericMethod(t1);
methodWithType.Invoke(this, null);
关于c# - 在不指定 T 的情况下调用字符串 GenericMethod<T>(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12096113/