[英]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.