8

考虑以下代码:

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# 时,他们显然必须使用某种方式来获取类的字符串文字。我只是希望它不会被硬编码到语言中。

4

2 回答 2

9
public static implicit operator TextType(String text) {
    return new TextType(text);
}
于 2010-01-24T18:46:49.080 回答
6

添加

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

到你的课?:)

于 2010-01-24T18:48:26.337 回答