我正在尝试解决 NHibernate NH-3260 的这个问题,并坚持覆盖具有通用接口约束的泛型方法,即参考基类。
例如我有以下模型:
public interface IMyGenericInterface<TId>
{
}
public class MyGenericClass<TId> : IMyGenericInterface<TId>
{
public virtual TRequestedType As<TRequestedType>()
where TRequestedType : MyGenericClass<TId>
{
return this as TRequestedType;
}
public virtual TRequestedType AsInterface<TRequestedType>()
where TRequestedType : class, IMyGenericInterface<TId>
{
return this as TRequestedType;
}
}
我正在尝试做以下事情
[Test]
public void GenericTypeConstraint()
{
var type = typeof (MyGenericClass<int>);
var method = type.GetMethod("As");
var genericArgument = method.GetGenericArguments()[0]; // TRequestedType : MyGenericClass<TId>
var typeConstraint = genericArgument.GetGenericParameterConstraints()[0]; // MyGenericClass<TId>
Assert.AreEqual(typeof(MyGenericClass<>),
typeConstraint); // This works
}
[Test]
public void GenericInterfaceConstraint()
{
var type = typeof (MyGenericClass<int>);
var method = type.GetMethod("AsInterface");
var genericArgument = method.GetGenericArguments()[0]; // TRequestedType : class, IMyGenericInterface<TId>
var typeConstraint = genericArgument.GetGenericParameterConstraints()[0]; // IMyGenericInterface<TId>
Assert.AreEqual(typeof (IMyGenericInterface<>),
typeConstraint); // Fails with
/*
Expected: <NHibernate.Test.DynamicProxyTests.GenericMethodsTests.IMyGenericInterface`1[TId]>
But was: <NHibernate.Test.DynamicProxyTests.GenericMethodsTests.IMyGenericInterface`1[TId]>
*/
}