我希望能够像初始化字符串一样初始化一个类:
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);
}
}
你认为呢?
"hello"
对应于IL中的ldstr "hello"
指令。 - Tim Robinsonstring str = "something";
没有通用规则,编译器在这种情况下只会为该情况执行它。 - Juan