Using static method from generic class

丶灬走出姿态 提交于 2021-02-05 11:13:26

问题


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?


回答1:


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.




回答2:


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.




回答3:


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
{
    ....
}



回答4:


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.



来源:https://stackoverflow.com/questions/44958494/using-static-method-from-generic-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!