简体   繁体   English

C#Object构造函数重载

[英]C# Object Constructor Overloads

I'm trying to have an overloaded constructor for a class. 我正在尝试为一个类重载一个构造函数。 I think this should be fairly simple, however I can't seem to make it work. 我认为这应该相当简单,但我似乎无法使其发挥作用。

Any ideas? 有任何想法吗?

    public SaveFile(string location)
    {
        // Constructor logic here
        //TODO: Implement save event.
        this.Save(location);
    }

    public SaveFile()
    {
        string location = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + "\\SaveFile.DAT";
        SaveFile(location);
    }

This doesn't compile correctly, and I can't figure out how to do make it work. 这不能正确编译,我无法弄清楚如何让它工作。

You have the wrong syntax for calling an overloaded constructor from within the default constructor. 您在默认构造函数中调用重载构造函数的语法错误。
To call an overloaded constructor in the same class, use this syntax: 要在同一个类中调用重载的构造函数,请使用以下语法:

public ClassName(parameters) : this(otherParameters)
{
   // logic
}

If you wanted to call a constructor in the base class, then you would use the base keyword instead of this . 如果你想在基类中调用构造函数,那么你将使用base关键字而不是this In your case the code would read: 在您的情况下,代码将读取:

public SaveFile() : this(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "SaveFile.DAT") {}
public SaveFile(string location)
{
    this.Save(location);
}
 public SaveFile() 
   : this(Environment.GetFolderPath(Environment.SpecialFolder.Personal) + "\\SaveFile.DAT")
    { 
    } 

However that really should be: 然而,这应该是:

 public SaveFile() 
   : this(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal),"SaveFile.DAT"))
    { 
    } 

Try this 尝试这个

public SaveFile(string location)
{
    // Constructor logic here
    //TODO: Implement save event.
    this.Save(location);
}

public SaveFile(): this(Environment.GetFolderPath(Environment.SpecialFolder.Personal) + "\\SaveFile.DAT")
{
}

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

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