-3

有什么办法可以在 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();
    }
}
4

2 回答 2

4

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

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

这在 MSDN 中的Using Constructors中有介绍。

话虽如此,在 C# 中,该类也必须不是static.

于 2013-08-23T18:25:15.727 回答
2

如果要将其转换为 C#,则需要更改几件事:

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

这应该适合你:

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);
    }
}
于 2013-08-23T18:26:44.303 回答