在调用基类的静态函数之前如何设置派生的静态成员

问题描述 投票:0回答:1

我有以下课程:

class Base<T> where T : Base<T>
{
    protected static string Source;

    public static List<T> Read()
    {
        return GetResource(Source);
    }
}

我希望此类作为其功能的基类,但每个派生类都必须具有不同的Source。我的问题是在调用Read之前不能确定Source是否已设置。我知道我可以问是否在调用GetResource之前设置了Source,但这不是重点。我需要在调用类的any静态成员之前进行设置。

通用参数不能有静态成员,所以我不能从那里获取它。

我尝试在派生类的静态构造函数中设置Source,但是只有当我调用派生类而不是Base中的成员时,才会调用该方法。

我尝试在静态Base构造函数内部使用可重写的方法,但这种方法也必须是静态的,并且不能覆盖静态方法。

当我手动设置Source时,有可能已经调用了Read-Function,因此我必须设置Source才可以调用它。

我知道我可以在Read中给Source作为参数,但我希望Read不带参数使用。

有什么方法可以确保在调用类的任何其他成员之前已经设置了源,以便任何相关代码都是派生类的[[inside,而不必由使用派生类?

我基本上希望它像这样工作:

class Derived : Base<Derived> { // somehow set Source Source = "This is my source"; } class User { private List<Derived> MyResources; public User() { MyResources = Derived.Read(); } }

注意:Source本质上是一个SQL语句,所以我认为Attribute或类似的东西是不够的。
c# generics static static-methods derived-class
1个回答
0
投票
好吧,我找到了答案。它不像我希望的那样漂亮,但它是我能想到的最好的。

我将使用一个接口来强制T的实例具有提供我的源的某种方法。

interface ISource { string GetSource(); }

然后我像这样将其实现到我的基类中:

class Base<T> where T : Base<T>, ISource, new() { public static List<T> Read() { // here I create an Instance to be able to call the Methods of T string source = (new T()).GetSource(); return GetResource(source); } }

派生类:

class Derived : Base<Derived>, ISource { public string GetSource() { return "This specific source"; } }

如此使用:

class User { public User() { List<Derived> myResources = Derived.Read(); } }

这当然会导致

Derived的每个实例都具有GetSource-方法,但是对我而言,这没什么大不了的。另外,由于它在Read方法中创建实例,因此根据Derived的构造方法,这可能会很耗时。在我的场景中,它只有标准构造函数。

因此请谨慎使用。
© www.soinside.com 2019 - 2024. All rights reserved.