我希望能够像初始化字符串一样初始化一个类:
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/