我正在尝试修复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]>
*/
}
答案 0 :(得分:2)
原因是您提供typeof (IMyGenericInterface<>)
作为预期值。这是开放式通用(IsGenericTypeDefinition = true
)。但是,typeConstraint
是封闭的通用(IsGenericTypeDefinition = false
)。
要使测试通过,请将断言更改为:
Assert.AreEqual(typeof (IMyGenericInterface<>),
typeConstraint.GetGenericTypeDefinition());