C# 自定义变量

标签 c#

我正在尝试创建自定义变量,但遇到了困难。

我对 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/

相关文章:

c# - 可以更改 LINQ 中的搜索方法吗?

c# - Task<T> 与 C# 中的异步委托(delegate)?

c# - 将列表转换为字符串列表

c# - 去掉 C 风格的多行注释

c# - 从 DataGridView 返回不同值的列表

c# - 在运行时在 NLog 中添加/删除日志文件

c# - 在 C#(或一般的 .NET)中,您可以屏蔽通过属性抛出异常的调用堆栈级别吗?

c# - 将 IP 字符串列表排序为具有空白条目的数字

c# - Asp.net core WebApi 中空值的自定义序列化

c# - 将单行从多维数组复制到新的一维数组