【问题标题】:Pass type to generic method (nested generic)将类型传递给泛型方法(嵌套泛型)
【发布时间】:2011-07-03 21:36:11
【问题描述】:

如果我没有TRootEntity,但只有它的TYPE,我如何调用以下方法:

public void Class<TRootEntity>(Action<IClassMapper<TRootEntity>> customizeAction) where TRootEntity : class;

最终目标是运行以下代码

var mapper = new ModelMapper();
mapper.Class<MyClass>(ca =>
{
    ca.Id(x => x.Id, map =>
    {
        map.Column("MyClassId");
        map.Generator(Generators.HighLow, gmap => gmap.Params(new { max_low = 100 }));
    });
    ca.Property(x => x.Something, map => map.Length(150));
});

用于创建动态NHibernateHBM。更多信息here

相关问题见here和here。

【问题讨论】:

标签: c# nhibernate dynamic nhibernate-mapping


【解决方案1】:

您不能通过传递运行时类型来编写通用方法来运行。

泛型需要在编译时具有类型。

您可能需要使用反射(请参阅 Ferreira 先生的回答关于如何做到这一点)。

【讨论】:

  • +1。请务必记住,泛型是在编译时外推的。
  • 请看我的更新。我添加了 2 个相关问题,表明至少在某些情况下是可能的。
  • 这两个相关问题都使用反射解决。这在编译后不必工作,而且肯定不会像纯泛型实现那样快。以此为例:obj.GetType().GetMethod("Find&lt;&gt;").MakeGenericMethod(type).Invoke() - 如果您发送的类型不符合通用约束,这将在运行时编译并失败。
【解决方案2】:

看看伟大的 Jon Skeet 的 this answer。您应该能够根据自己的需要进行调整。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-12
    • 1970-01-01
    • 2022-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多