簡體   English   中英

C# - 與字符串構造函數類似,但不能返回結果

[英]C# - Similar as string constructor but can't return result

好的家伙,我是C#編程的新手,今天我試圖創建構造函數,它將像一個String構造函數但問題是我必須在使用它之后返回結果,但是因為我知道構造函數不能有返回類型,不能是靜態的

using System;


class StringA {
  public StringA(char x, int y) {
    string res = "";
    string ConvertedChar = Convert.ToString(x);

    for (int i = 0; i < y; i++) {
      res += ConvertedChar;
    }
    // How to return string res?
  }

}
class MainClass {
  static void Main() {
    Console.WriteLine(new StringA('B', 15));
  }
}

你可以做的是覆蓋類StringA的ToString()方法。

    class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(new StringA('B', 15));
        Console.Read();
    }
}


class StringA
{

    string res = "";

    public StringA(char x, int y)
    {
        string ConvertedChar = Convert.ToString(x);

        for (int i = 0; i < y; i++)
        {
            res += ConvertedChar;
        }
    }

    public override string ToString()
    {
        return res;
    }

}

您在尋找靜態工廠方法嗎?

public static string CreateRepeatedString(char x, int y) {
   return new string(x, y);
}

您可以通過以下方式使用關鍵字out

class StringA
{
    public StringA(char x, int y, out string res)
    {
        res = "";
        string ConvertedChar = Convert.ToString(x);

        for (int i = 0; i < y; i++)
        {
            res += ConvertedChar;
        }
        // or even shorter
        // res = new string(x, y);
      }
}

然后你可以將一些字符串傳遞給constrctor並在構造函數中更改它的值。 然后你可以使用它:

class MainClass
{
    static void Main()
    {
        string res;
        Console.WriteLine(new StringA('B', 15, out res));
    }
}

也許你可以為你的班級創建一個公共訪問者,或者你更願意需要一個靜態工廠方法,如@Joey在他的回答中所說的那樣?

見下面的例子:

using System;

namespace YourNamespace {
  class StringA {

    private string privateVal = "";
    public string PublicVal {
      get {
        return this.privateVal;
      }
      set {
        this.privateVal = value;
      }
    }
    public StringA(char x, int y) {
      string res = "";
      string ConvertedChar = Convert.ToString(x);

      for (int i = 0; i < y; i++) {
        res += ConvertedChar;
      }
      // How to return string res?
      this.privateVal = res; //assign res to your accessor
    }

  }
  class MainClass {
    static void Main() {
      //then you can access the public property
      Console.WriteLine(new StringA('B', 15).PublicVal);
    }
  }
}

除了上述答案,您還可以添加隱式運算符

class StringA
{
    private readonly string instance;
    public StringA(char x, int y)
    {
        string res = "";
        string ConvertedChar = Convert.ToString(x);

        for (int i = 0; i<y; i++)
        {
            res += ConvertedChar;
        }
        this.instance = res;
    }

    public static implicit operator string(StringA d) => d.instance;   
}  

這可以用作:

string str = new StringA('x', 10);
Console.WriteLine(new StringA('y',100));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM