我正在尝试制作自定义变量,但遇到了麻烦。
我仍然对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'的异常。
最佳答案
这是因为隐式运算符是递归调用的。您需要这样实现您的结构,以某种方式封装您的字符串变量。
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());
您可以参考文档here。
关于c# - C#自定义变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50976944/