2

我正在尝试制作自定义变量,但被卡住了。

我还是 C# 的新手,所以我猜我只是不知道发生了什么。

struct MyCustomStringVariable
{
    public static implicit operator MyCustomStringVariable(string input)
    {
        return input;
    }
}

class Program
{
    static MyCustomStringVariable myCustomString = "This is a string!";

    static void Main(string[] args)
    {
        Console.WriteLine(myCustomString);
        Console.ReadLine();
    }
}

抛出以下异常

System.StackOverflowException:“引发了‘System.StackOverflowException’类型的异常。”

4

2 回答 2

4

这是因为代码卡在无限循环中。您的隐式运算符将调用自身,因为它返回原始输入字符串,该字符串不会因为定义的运算符而引发异常。

public static implicit operator MyCustomStringVariable(string input)
{
    return input; // returning string type will call this method again
}

应该

public static implicit operator MyCustomStringVariable(string input)
{
    // and use input somewhere on the returned type
    return new MyCustomStringVariable(); 
}

也就是说,您可能没有理由定义一个名为的类型MyCustomStringVariable,但这很难说,因为您从未共享此代码或您打算如何使用它。


我的最终目标是在脑海中可视化制作字符串变量的过程,以便更好地理解其背后的概念。

我不确定您的自定义结构或其隐式运算符如何符合此目标。为什么不只使用 type string

static string myCustomString  = "This is a string!";
于 2018-06-21T20:33:13.497 回答
1

这是因为隐式运算符是递归调用的。你需要这样实现你的结构,以某种方式封装你的字符串变量。

struct MyCustomStringVariable
{
    private string value;

    public MyCustomStringVariable(string input)
    {
        value = input;
    }

    public static implicit operator MyCustomStringVariable(string input)
    {
        return new MyCustomStringVariable(input);
    }

    public string GetValue()
    {
        return value;
    }
}

然后,像这样称呼它

Console.WriteLine(myCustomString.GetValue());

你可以参考这里的文档。

于 2018-06-21T20:39:32.503 回答