0

我正在尝试解决 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]>
    */
}
4

1 回答 1

3

这样做的原因是您提供typeof (IMyGenericInterface<>)了预期值。这是开放的泛型 ( IsGenericTypeDefinition = true)。但是,typeConstraint是封闭的泛型 ( IsGenericTypeDefinition = false)。

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

Assert.AreEqual(typeof (IMyGenericInterface<>),
                typeConstraint.GetGenericTypeDefinition());
于 2013-06-04T10:17:20.627 回答