Pass type to generic method (nested generic)
Asked Answered
C

2

8

How can I invoke following method while I have not TRootEntity, but have just its TYPE:

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

final goal is to run following code

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));
});

It is used to create dynamic NHibernate HBM. More info available here

As related question see here and here.

Chivalry answered 3/7, 2011 at 11:48 Comment(1)
possible duplicate of How to use reflection to call generic Method?Aloisia
F
16

You cannot code Generic methods to run by passing a runtime Type.

Generics need to have the type at compile time.

You may need to use reflection (see answer of mr. Ferreira that point on how to do that).

Fragmentation answered 3/7, 2011 at 13:18 Comment(3)
+1. It is important to remember that generics are extrapolated at compile time.Canst
Please see my update. I have added 2 related questions that shows it is possible at least in certain situations.Chivalry
both of those related question are solved using reflection. That does not have to work after you compile and surely won't work as fast as a pure generic implementation. Take this for example: obj.GetType().GetMethod("Find<>").MakeGenericMethod(type).Invoke() - if you send a type that does not adhere to the generic constrains this will compile and fail at runtime.Fimble
F
14

Have a look at this answer from the great Jon Skeet. You should be able to adapt it to your needs.

Fetation answered 3/7, 2011 at 13:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.