字符串连接的运算符重载 c#.net

问题描述 投票:0回答:1

我的自定义数据类型为

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;

}

我正在使用这个AppIdenty,就像这样

AppIdentiy myIdentity  = '[email protected]';

string email = myIdentity; //setting the variable email with the value '[email protected]'

string comment  = "this is user email address '" + myIdentity + "' generated by xyz app'; //this is not working, I am expecting here when I use '+' operator with my datatype its value should populate here like 

“这是 xyz 应用生成的用户电子邮件地址 '[email protected]'”

我不知道如何在我的 AppIdentiy 类中装饰 + 运算符重载

c# operator-overloading
1个回答
0
投票

在这种情况下,您实际上正在做更像

string.Concat
的事情,其中非
string
操作数的存在意味着它将使用
ToString()
方法。所以:不要重载运算符:想想
override
:

// in this case, we'll use the operator you already wrote, but we could embed
// your logic directly, if preferable
public override string ToString() => (string)this;
© www.soinside.com 2019 - 2024. All rights reserved.