带有自引用约束的接口的GetGenericParameterConstraints



我正试图修复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]>
    */
}

这样做的原因是您将typeof (IMyGenericInterface<>)作为期望值提供。这是开放泛型(IsGenericTypeDefinition = true)。而typeConstraint是封闭泛型(IsGenericTypeDefinition = false)。

要使测试通过,请将断言更改为:

Assert.AreEqual(typeof (IMyGenericInterface<>),
                typeConstraint.GetGenericTypeDefinition());

相关内容

  • 没有找到相关文章

最新更新