[英]How Can i call other functions in a class from special function(Just with their string names) in C#?
[英]How can I make a class in C# that I can initialize just like a string?
我希望能夠像初始化字符串一樣初始化類:
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
好吧,你可以創建一個從字符串到你的類型的隱式轉換......但我個人很少這樣做。 一類是做的一個例子是XNamespace
從LINQ到XML。 你的班級真的只有一個字符串成員嗎? 如果是這樣,也許它是合適的。 或者它可能只有一個字符串和一些其他字段通常可以默認...但在大多數情況下,我不希望從string
的轉換是合適的。
換句話說:你的用戶是否真的會以與字符串完全相同的方式來思考你的類? 它是否有效地成為字符串的包裝? 如果您能提供更多詳細信息,我們可以提供更多建議。
不,編譯器不會將“hello”轉換為new System.String("hello")
- 這只會導致遞歸問題,當然也會導致內部破壞。 IL直接支持C#編譯器使用的字符串常量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.