【问题标题】:Using string constants in implicit conversion在隐式转换中使用字符串常量
【发布时间】:2011-01-08 20:27:17
【问题描述】:

考虑以下代码:

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 节。

标签: c# string operators implicit implicit-conversion


【解决方案1】:
public static implicit operator TextType(String text) {
    return new TextType(text);
}

【讨论】:

  • 修复文本 != 值 - 不过你的速度更快 :)
  • 我无法相信我是如何错过运算符重载的。我有一种感觉,该方法必须属于 String 类...谢谢。
【解决方案2】:

添加

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

到你的班级? :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-13
    • 1970-01-01
    • 2021-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多