简体   繁体   English

使用泛型类中的静态方法

[英]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(); 不可能完全按照您的要求进行操作,但是由于该方法根本不使用T ,因此可以只使用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(); 调用BaseFactory.UpdateDataBase_static(); you need a class BaseFactory . 您需要一个BaseFactory类。 Inherite the generic BaseFactory<T> from it. BaseFactory<T>继承通用BaseFactory<T>

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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