C#:按方法在构造函数中设置属性

我开始理解C#和OOP,并且遇到一个我似乎无法解决的问题.我有一个名为DataSet的类,它应该包含几个属性(以System.Collections.Generic.Dictionary对象的形式).在类中,我有从数据库加载数据的方法,这些方法应该用于初始化DataSet.基本上,当我从Main方法实例化它时,我希望DataSet对象设置所有属性.

我所拥有的是以下内容(省略细节):

public class DataSet
{
    public IDictionary<string, MyClass1> Property1 { get; set; };
    public IDictionary<string, MyClass2> Property2 { get; set; };
    public IDictioanry<string, MyClass3> Property3 { get; set; };

    public DataSet()
    {
            Property1 = new Dictionary<string, MyClass1>();
            Property2 = new Dictionary<string, MyClass2>();
            Property3 = new Dictionary<string, MyClass3>();
        // Set Property1
        // Set Property2
        // Set Property3 (can only be done when Property1 is known)
    }

    private void GetProperty1(/* something? */)
    {
        // Loads the data from a database.
    }

    private static Dictionary<string, MyClass1> GetProperty1Alternative(DataSet dataSet)
    {
        // Same thing but static, so needs instance ref.
    }

    // Similarly for Property2 and Property3
}

我想要的是在构造函数中设置属性.我的问题基本上是:

>我正在以正确的方式做这件事吗?
>如果是,我应该使我的方法是静态的(并通过引用方法传递实例),这将要求类DataSet是静态的(及其所有属性),或者有没有办法做我正在做的事情而不做DataSet静态?
>一个重要的问题是Property3只能在Property1已知/设置后设置.我不知道这是否可能……

任何帮助是极大的赞赏.

最佳答案

Is what I am doing at all the right way to do it?

你不是那么遥远.我想很多人都会把你的Get函数混淆成传统的’getter’,所以你应该重命名它.

If yes, should I make my methods static (and pass an instance by reference to the methods), which would require the class DataSet to be static (and all its properties) or is there a way to do what I am doing without making DataSet static?

您可以使方法实际上将数据加载为静态,并且您不需要传递实例 – 您只需返回数据即可. (我已更改了功能名称).从实例/构造函数调用静态方法很好,但不是相反.

public DataSet()
{
        Property1 = LoadProperty1();
        Property2 = LoadProperty2();
        Property3 = LoadProperty3();//can only be done when Property1 is known
}

private static Dictionary<string, MyClass1> LoadProperty1()
{
    // load data
}

An important issue is that Property3 can only be set once Property1 is known/set. I have no idea if that is possible…

如您所见,这在上面的代码中得到了解决.

点赞