【问题标题】:Is there a way to add two numbers using a private constructor in C#有没有办法在 C# 中使用私有构造函数来添加两个数字
【发布时间】:2017-10-20 10:36:20
【问题描述】:

我正在尝试使用私有构造函数添加两个数字,但到目前为止都失败了。有没有办法添加它们?

class Program { 
     static void Main(string[] args) { 
         int add = Addition.add(); //Console.WriteLine() 
         Console.ReadKey(); 
     }
} 
public class Addition { 
     public static int num1, num2; 
     private Addition() { 
          Console.WriteLine("Enter two numbers"); 
          num1 = int.Parse(Console.ReadLine()); 
          num2 = int.Parse(Console.ReadLine()); 
    } 
    public static int add() { 
          return num1 + num2; 
    } 
} 

【问题讨论】:

  • 请编辑您的问题并将其添加到问题本身。还要说明这段代码有什么问题

标签: c# constructor private


【解决方案1】:

这是一个例子:

public class Example {
    public int Result {get; private set;}
    private Example(int x, int y){
       Result = x + y;
    }
    public static Example Create(int x, int y){
         return new Example(x,y);
    }   
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-10
    • 1970-01-01
    • 2020-06-28
    • 2014-05-13
    • 1970-01-01
    • 2015-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多