我正在尝试创建自定义变量,但遇到了困难。
我对 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: 'Exception of type 'System.StackOverflowException' was thrown.'
最佳答案
这是因为代码陷入了无限循环。您的隐式运算符将调用自身,因为它返回原始输入字符串,该字符串不会因定义的运算符而引发异常。
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
的类型,但这很难说,因为您从不共享此代码或打算如何使用它。
My final goal is to visualize the process of making a string variable in my head so that I can better understand the concept behind it.
我不确定您的自定义结构或其隐式运算符如何符合此目标。为什么不直接使用string
类型?
static string myCustomString = "This is a string!";
关于C# 自定义变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50976944/