开发者

Is there a way to new a class that's the same type as another class without directly specifying it

I have extension method that does something like this

public static void DoStuff(this ObjectContext context)
{
    using(var newContext = new MyEntitiesContext())
    {
        // do stuff
        newContext.SaveChanges();
    }
    context.SaveChanges();
}

I wa开发者_开发技巧s wondering if there a way to new a context of the same type as the context passed in instead of specifying MyEntitiesContext?

Thanks in advance


If you don't mind reflection:

var context = Activator.CreateInstance(context.GetType());

Now you either need a base Type or - if you still don't mind reflection - you can simply call the method by name. Or, since you are using C#4 you could go with dynamic.

Edit: You could also Go this way:

public static void DoStuff<T>(this T context) where T : ObjectContext, new()
{
    using(var newContext = new T())
    {
         // do stuff
        newContext.SaveChanges();
    }
    context.SaveChanges();
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜