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

8

Consider the following code:

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隐式操作符重载来扩展String类,但有没有一种方式可以将文字字面值分配给另一个类(由方法或其他东西处理)?

String是一个引用类型,所以在开发C#时,他们显然必须使用某种方式将字符串字面值传递给该类。我只希望它没有被硬编码到语言中。


请参阅规范的第10.10.3节以获取详细信息。 - Eric Lippert
2个回答

9
public static implicit operator TextType(String text) {
    return new TextType(text);
}

修复文本!=值 - 你虽然更快 :) - Benjamin Podszun
1
我简直不敢相信我错过了运算符重载是双向的这一点。我有一种感觉,这个方法应该属于String类...谢谢。 - Kornelije Petak

6

添加

public static implicit operator TextType(string content) {
  return new TextType(content);
}

你想向你的班级介绍吗? :)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接