开发者

use Insert<T>(T o) with an object type

I have a method

public void Insert<T>(T o开发者_StackOverflow) 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's an object T == object, but I need it to be the x.GetType() type

anybody knows how to do this ?


You'd basically have to call it via reflection (e.g. using MethodInfo.MakeGenericMethod). Generics is about providing compile-time type safety, whereas you don't know the type at compile time. Alternatively you can use dynamic typing if you're on C# 4.

Using reflection is a pain in terms of:

  • Lack of type safety at compile time, so errors can only be detected in tests (or in production!)
  • Performance
  • Ease of coding

If you're using C# 4, the dynamic typing solution would be:

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


You can do it using reflection:

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

But that's very inefficient... if you find yourself in a situation where you need to do that, you should probably reconsider your design

If you can, try to provide a non generic version of your method:

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

(you also need a non-generic version of Set)


If you know the type, simply cast it:

r.Insert((YourType)x);

If you don't know it: See the other answers.


You need to call the Insert command via reflection in order to specify the type at runtime.

I would add a second overload of the insert method like this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜