不可见的构造函数,尽管使用公共访问修饰符?

时间:2015-04-23 01:00:04

标签: c#

我编写了一个具有多个重载的类,但是当我尝试在类之外使用它们时,只能使用默认构造函数。否则我收到一条错误,指出不存在这样的构造函数。

        public Module()//default Module Class
        {
            Code = "Undefined";
            Title = "Undefined";
            Credits = 0;
            Mark = 0;
            ExamWeighting = 0;
            ExamMark = 0;
            CourseWorkNumber = 1;
            Term = "AY";
            CourseWork1Name = "Undefined";
            CourseWork1Type = "Undefined";
            CourseWork1Weight = 1;
            CourseWork1Mark = 0;
        }

        public Module(string code, string title, int credits, string moduleTerm, double exWeight, double exMark, string cW1Name, string cW1Type, double cW1Weight, double cW1Mark)
        {
            Code = code;
            Title = title;
            Credits= credits;
            Mark = 0;
            ExamWeighting = exWeight;
            ExamMark = exMark;
            CourseWorkWeight = 1.0 - exWeight;
            CourseWorkNumber = 1;
            Term = moduleTerm;
            CourseWork1Name = cW1Name;
            CourseWork1Type = cW1Type;
            CourseWork1Weight = cW1Weight;
            CourseWork1Mark = cW1Mark;

        }

我确保我有正确数量和类型的参数,除非我当然错过了什么。

                    string code = tempArray[0];
                    string title = tempArray[1];
                    int credits = Convert.ToInt16(tempArray[2]);
                    string moduleTerm = tempArray[3];
                    double exWeight = Convert.ToDouble(tempArray[4]);
                    double exMark = Convert.ToDouble(tempArray[5]);
                    string cW1Name = tempArray[10];
                    string cW1Type = tempArray[11];
                    double cW1Weight = Convert.ToDouble(tempArray[12]);
                    double cW1Mark = Convert.ToDouble(tempArray[13]);


                    // (string code, string title, int credits, string moduleTerm, double exWeight, double exMark, string cW1Name, string cW1Type, double cW1Weight, double cW1Mark)
                    tempModule = new Module(code, title, credits, moduleTerm, exWeight, exMark, cW1Name, cW1Type, cW1Weight, cW1Mark);

1 个答案:

答案 0 :(得分:1)

具有一英里长的参数列表是反模式。你刚刚通过搞乱电话就发现了为什么会这样,因为你要么:

  • 参数数量错误

  • 您使用
  • 的参数中的类型不正确

在通话现场。

如果您不可避免地需要大量参数,那么您可以考虑使用封装所有这些参数的选项类。这也允许合理的默认值。所以

public class ModuleOptions
{
    public ModuleOptions()
    {
        //supply sensible defaults here
        Code = "Not set";
        Title = "Not set";
        //etc
    }
    public string Code{get;set;}
    public string Title{get;set;}
    //etc...
}

然后

public class Module
{
    public Module(ModuleOptions options)
    {
        this.Code = options.Code;
        //etc...
    }
}

现在您的呼叫网站看起来像

var opts = new ModuleOptions
    {
        Code = "1234",
        //etc
    };
var module = new Module(opts);

现在,您可以更轻松地查看正在发生的事情,并且您不太可能搞砸了您的电话。