简体   繁体   中英

Using static method from generic class

I have problem as above. My code:

public abstract class BaseFactory<T> where T: class
{
    protected static dbModelContainer context = new dbModelContainer();

    public static int UpdateDataBase_static()
    {
        return context.SaveChanges();
    }
 }

and my question is how can I call

BaseFactory.UpdateDataBase_static();

instead of:

BaseFactory<SomeClass>.UpdateDataBase_static();

Any ideas?

You can't, because there is no such method. The closest is to have a non-generic base that the generic class inherits from. Then you can have a method there that doesn't depend on the parameterising type.

You don't.

You always need to supply the generic type arguments when accessing a class, even though you aren't using that type argument in your method. Since you don't actually use the generic type in the method it means you could move that method out of that class, and into one that isn't generic, but for as long as it's in that class you'll need to supply the generic argument.

It's not possible to do exactly what you're asking, but since the method doesn't use T at all, you can just use BaseFactory<object>.UpdateDataBase_static(); without specifying any particular class.

But as an editorial comment, in general a method in a generic class that never uses the generic parameter probably shouldn't be there.

To call BaseFactory.UpdateDataBase_static(); you need a class BaseFactory . Inherite the generic BaseFactory<T> from it.

public abstract class BaseFactory
{
    protected static dbModelContainer context = new dbModelContainer();

    public static int UpdateDataBase_static()
    {
        return context.SaveChanges();
    }
 }

public abstract class BaseFactory<T>:BaseFactory where T: class
{
    ....
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM