C#/.Net字符串拼接运算符重载问题:自定义AppIdentity无法参与+拼接
问题:自定义类型AppIdentity的字符串拼接异常
我定义了如下自定义数据类型:
public class AppIdentiy { public string ID { get; set; } public static implicit operator AppIdentiy(string userID) { var result = new AppIdentiy() { ID = userID }; return result; } public static implicit operator string(AppIdentiy identity) { if (identity is null) return string.Empty; else if (string.IsNullOrEmpty(identity.ID)) return string.Empty; return identity.ID; } //public static string operator +(AppIdentiy a) => a.ID; }
我这样使用该类型:
AppIdentiy myIdentity = "nkg@xyz.com"; string email = myIdentity; //成功将email赋值为'nkg@xyz.com' string comment = "this is user email address '" + myIdentity + "' generated by xyz app"; //此代码无法正常工作,预期得到结果:
"this is user email address 'nkg@xyz.com' generated by xyz app"
我不清楚该如何在AppIdentity类中正确实现+运算符重载。
解决方案
核心问题:类名拼写错误
首先你代码里存在一个低级错误:类定义时写的是AppIdentiy(少了一个t),但使用时的变量类型是AppIdentity,这会直接导致编译失败,修正类名拼写后,已有的隐式转换就能自动生效,字符串拼接会把AppIdentity实例转为字符串,不需要额外重载+运算符。
可选优化方案
如果想让类型的字符串表现更通用,推荐重写ToString()方法,这是C#中处理对象转字符串的标准方式,适配更多场景(比如日志输出、字符串格式化):
public override string ToString() { return ID ?? string.Empty; }
若一定要重载+运算符
+是二元运算符,不能只定义一元版本,需要实现字符串与AppIdentity双向拼接的重载:
public static string operator +(string left, AppIdentiy right) { return left + (right ?? string.Empty); } public static string operator +(AppIdentiy left, string right) { return (left ?? string.Empty) + right; }
不过最简洁可靠的方式还是修正类名拼写,依赖已有的隐式转换或重写ToString()方法。
内容的提问来源于stack exchange,提问作者Neeraj Kumar Gupta
相关产品推荐
相关产品推荐

