如何使用其他名称创建新的System.String类型?

时间:2011-06-23 08:27:29

标签: .net vb.net

我尝试逐步描述我的问题,因为我不知道如何用正确的编程术语来说明。

当我使用 System.String 类型时,我会执行以下操作:

  1. 声明类型:Dim Str1 as String
  2. 指定其值:Str1 = "This is a string"
  3. 我想创建一个类似 System.String 类型的新类型,但名称不同。例如,我想为此字符串创建 UrlString 类型:

    1. 声明类型:Dim Str2 as UrlString
    2. 指定其值:Str2 = "http://www.example.com"
    3. 我的问题是:如何创建 UrlString 类型?

      原因:我想创建UrlString类型以帮助我识别内容的值。例如,UrlString类型表示字符串是url格式,PhoneString表示字符串是电话格式,CreditCardString类型表示字符串是信用卡格式,依此类推。

      更新

      感谢Marc Gravell和GSerg。这是解决方案:

      Class UrlString
          Private ReadOnly value As String
      
          Public Sub New(ByVal value As String)
              Me.value = value
          End Sub
      
          Public Shared Widening Operator CType(ByVal value As String) As UrlString
              Return New UrlString(value)
          End Operator
      
          Public Shared Widening Operator CType(ByVal u As UrlString) As String
              Return u.value
          End Operator
      
          Public Overrides Function GetHashCode() As Integer
              Return If(value Is Nothing, 0, value.GetHashCode())
          End Function
      
          Public Overrides Function Equals(ByVal obj As Object) As Boolean
              Return String.Equals(value, DirectCast(obj, String))
          End Function
      
          Public Overrides Function ToString() As String
              Return value
          End Function
      End Class
      

1 个答案:

答案 0 :(得分:8)

您需要添加一个隐式转化运算符,从stringUrlString才能生效。在C#中:

class UrlString
{
    private readonly string value;
    public UrlString(string value) { this.value = value; }
    public static implicit operator UrlString(string value)
    {
        return new UrlString(value);
    }
    public override int GetHashCode()
    {
        return value == null ? 0 : value.GetHashCode();
    }
    public override bool Equals(object obj)
    {
        return string.Equals(value, (string)obj);
    }
    public override string ToString()
    {
        return value;
    }
}

然后:

UrlString foo = "abc";