在隐式转换中使用字符串常量

Kor*_*tak 8 c# string operators implicit implicit-conversion

请考虑以下代码:

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.
Run Code Online (Sandbox Code Playgroud)

但是如果可能的话,我希望能够做到以下几点.

TextType textFromStringConstant = "SomeOtherText";
Run Code Online (Sandbox Code Playgroud)

我无法使用TextType隐式运算符重载扩展String类,但有没有办法将文字字符串分配给另一个类(由方法或其他东西处理)?

String是一个引用类型,因此当他们开发C#时,他们显然必须使用某种方式来获取类的字符串文字.我只是希望它不是硬编码的语言.

Cha*_*ion 9

public static implicit operator TextType(String text) {
    return new TextType(text);
}
Run Code Online (Sandbox Code Playgroud)


Ben*_*zun 6

public static implicit operator TextType(string content) {
  return new TextType(content);
}
Run Code Online (Sandbox Code Playgroud)

到你的班级?:)