构造函数中的构造函数

本文关键字:构造函数 | 更新日期: 2023-09-27 18:28:52

在C#中有什么方法可以做到这一点吗?我不能在C#代码中使用this(int,int)。你能给我写一些类似的代码吗?这些代码将用C#编写,并将做同样的事情?谢谢!:)

public class JavaApplication2
{
    public static class SomeClass 
    {
        private int x;
        private int y;
        public SomeClass () { this(90,90); }
        public SomeClass(int x, int y) { this.x = x; this.y = y; }
        public void ShowMeValues ()
        {
            System.out.print(this.x);
            System.out.print(this.y);
        }
    }
    public static void main(String[] args) 
    {
        SomeClass myclass = new SomeClass ();
        myclass.ShowMeValues();
    }
}

构造函数中的构造函数

是的,C#可以链接构造函数:

public SomeClass() :this(90,90) {}
public SomeClass(int x, int y) { this.x = x; this.y = y; }

这在MSDN的"使用构造函数"中有介绍。

也就是说,在C#中,类也必须不是static

如果您想将其转换为C#,需要更改以下几点:

  1. 主要的问题是您已经将SomeClass声明为静态。它不会编译,因为静态类不能有实例成员。您需要删除static关键字
  2. 要从另一个构造函数调用构造函数,需要在构造函数参数之后使用: this(...)(或: base(...)来调用父类的构造函数)
  3. 对于.NET应用程序,您需要使用System.Console而不是System.out

这应该对你有用:

public class SomeClass 
{
    private int x;
    private int y;
    public SomeClass () : this(90,90) { }
    public SomeClass(int x, int y) { this.x = x; this.y = y; }
    public void ShowMeValues ()
    {
        Console.WriteLine(this.x);
        Console.WriteLine(this.y);
    }
}