Use Insert <T> (T o) with Object Type

I have a method

public void Insert<T>(T o) where T : class
{
            c.Set<T>().Add(o);
}

I need to use it with an object type

object x = ....

r.Insert(x);

but since it is an object T == object, but I need its typex.GetType()

Does anyone know how to do this?

+3
source share
4 answers

You basically need to call it using reflection (e.g. using MethodInfo.MakeGenericMethod). Generics is type compilation type security, while you don’t know the type at compile time. Alternatively, you can use dynamic typing if you are in C # 4.

Using reflection is a pain in terms of:

  • There is a lack of type safety during compilation, so errors can only be detected in tests (or in production!)
  • Performance
  • Ease of coding

# 4, :

dynamic d = x;
r.Insert(d);
+5

, :

var method = r.GetType().GetMethod("Insert").MakeGenericMethod(new[] { x.GetType() });
method.Invoke(r, new[] { x });

... , , , ,

, :

public void Insert(object o) where T : class
{
    c.Set(o.GetType()).Add(o);
}

( Set)

+4

If you know the type, just do it:

r.Insert((YourType)x);

If you do not know this: see other answers.

+2
source

You need to invoke the Insert command with reflection to indicate the type at runtime.

I would add a second overload of the insert method, for example:

private static readonly MethodInfo setMethod = typeof(WhateverCIs).GetMethod("Set");

public void Insert(object o)
{
    var t = o.GetType();

    var set = setMethod.MakeGenericMethod(new[] { t });
    (set.Invoke(c) as WhateverSetReturns).Add(o);
}
+1
source

All Articles