开发者

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

开发者 https://www.devze.com 2023-01-19 17:06 出处:网络
I have extension method that does something like this public static void DoStuff(this ObjectContext context)

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

精彩评论

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