c# - 如何在 C# 中创建一个可以像字符串一样初始化的类?

标签 c# .net

我希望能够像初始化字符串一样初始化一个类:

string str = "hello";
MyClass class = "hello";

我真的不知道 string str = "hello"; 到底做了什么。我假设 "hello" 被编译器翻译成 new System.String("hello"); 但我不确定。也许是不可能的,或者我错过了一些非常基本的东西;如果是这样,请原谅我的无知:)。我想要做的是一个像字符串一样工作但自动将字符串存储在文件中的类。

好的,这是我在阅读您的回答后的代码:

class StringOnFile
{
    private static string Extension = ".htm";
    private string _FullPath;
    public bool Preserve = false;

    public string FullPath
    {
        get
        {
            return _FullPath;
        }
    }

    public static implicit operator StringOnFile(string value)
    {
        StringOnFile This = new StringOnFile();
        int path = 0;

        do{
            path++;
            This._FullPath = Path.GetFullPath(path.ToString() + Extension);
        } 
        while(File.Exists(This._FullPath));

        using (StreamWriter sw = File.CreateText(This._FullPath))
        {
            sw.Write(value);
        }

        return This;
    }

    public static implicit operator string(StringOnFile stringOnFile)
    {
        using (StreamReader sr = File.OpenText(stringOnFile._FullPath))
        {
            return sr.ReadToEnd();
        }
    }

    ~StringOnFile()
    {
        if(!Preserve) File.Delete(FullPath);
    }
}

你怎么看?

最佳答案

尝试以下操作

class MyClass {
    public static implicit operator MyClass(string value) {
        // Custom logic here 
        return new MyClass();
    }
}

void Example() {
  MyClass v1 = "data";
}

这将得到您正在寻找的最终结果。但是我建议不要使用这种方法。您最终会遇到一些隐式转换的陷阱。最好有一个接受 string

的构造函数

关于c# - 如何在 C# 中创建一个可以像字符串一样初始化的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3152460/

相关文章:

C#模板引擎

c# - Adapter.Fill 需要很长时间

c# - 优化字典键的内存要求

c# - 为什么我的模型属性在尝试 POST 时为空?

c# - 可以使一个 Hello World exe 在所有版本的 .NET 中工作吗? (2.0 和 4.5)

c# - 为什么以及何时继承 Collection<T>

c# - 无法从 SharpPcap.RawCapture 转换为 PacketDotNet.Packet

C# WPF 获取错误 - System.InvalidOperationException :

c# - 即兴 : Could not load type because it attempts to implement a class as an interface

c# - 仅检测 Unity 中的特定键盘组合