我使用的库包含此方法:
T TheirMethod<T>() where T : Base; // T must inherit from Base
在我的代码中,有这样的方法:
T MyMethod<T>() // it can be any T here
{
if (!typeof(T).IsSubclassOf(typeof(Base)))
throw new Exception("I'm fine with crashing at runtime here");
return x.TheirMethod<T>(); // DOES NOT COMPILE
}
当然这不会编译,因为编译器不够聪明,无法静态证明我的T
是Base
。 (我无法向MyMethod
添加where
约束,因为它实现了另一个第三方接口。
我的问题是:我该如何称呼它?我希望在运行时完成此检查。
您可以使用反射来调用该方法。但是,您应该考虑反射的性能影响。
T MyMethod<T>()
{
if (!typeof(T).IsSubclassOf(typeof(Base)))
throw new Exception("I'm fine with crashing at runtime here");
return (T) typeof(TheirClass).GetMethod("TheirMethod").MakeGenericMethod(typeof(T)).Invoke(x, null);
}
使用将类型约束检查延迟到运行时的特殊dynamic
类型:
return ((dynamic)x).TheirMethod<T>();
(我在写问题的中途找到了答案,但无论如何我都会发布它,以防它对某人有用。