質問

次のコードを検討してください。

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);
}

あなたのクラスに? :)

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top