在隐式转换中使用字符串常数
-
22-09-2019 - |
题
考虑以下代码:
public class TextType {
public TextType(String text) {
underlyingString = text;
}
public static implicit operator String(TextType text) {
return text.underlyingString;
}
private String underlyingString;
}
TextType text = new TextType("Something");
String str = text; // This is OK.
但是,如果可能的话,我希望能够做以下操作。
TextType textFromStringConstant = "SomeOtherText";
我无法使用TextType隐式运算符过载扩展字符串类,但是是否有任何方法可以将字符串分配给另一个类(通过方法或其他类别处理)?
字符串是一种参考类型,因此当他们开发C#时,显然必须使用某种方法来获得类字符串的字体。我只是希望它不会被编码为语言。
解决方案
public static implicit operator TextType(String text) {
return new TextType(text);
}
其他提示
添加
public static implicit operator TextType(string content) {
return new TextType(content);
}
上课吗? :)
不隶属于 StackOverflow