語言

INameCreationService.ValidateName(String) 方法

定義

會取得一個值,表示指定名稱是否有效。

public:
 void ValidateName(System::String ^ name);
public void ValidateName(string name);
abstract member ValidateName : string -> unit
Public Sub ValidateName (name As String)

參數

name
String

這個名字值得驗證。

範例

以下程式碼範例提供了一個 INameCreationService.IsValidName 方法實作範例,使用字串驗證方案,檢查指定字串的每個字元以判斷該字串是否為有效名稱。 若字串無效,方法會拋出例外。

// Throws an exception if the specified name does not contain 
// all valid character types.
virtual void ValidateName( String^ name )
{
   for ( int i = 0; i < name->Length; i++ )
   {
      Char ch = name[ i ];
      UnicodeCategory uc = Char::GetUnicodeCategory( ch );
      switch ( uc )
      {
         case UnicodeCategory::UppercaseLetter:
         case UnicodeCategory::LowercaseLetter:
         case UnicodeCategory::TitlecaseLetter:
         case UnicodeCategory::DecimalDigitNumber:
            break;

         default:
            throw gcnew Exception( String::Format( "The name '{0}' is not a valid identifier.", name ) );
      }
   }
}
// Throws an exception if the specified name does not contain 
// all valid character types.
public void ValidateName(string name)
{
    for(int i = 0; i < name.Length; i++)
    {
        char ch = name[i];
        UnicodeCategory uc = Char.GetUnicodeCategory(ch);
        switch (uc) 
        {
            case UnicodeCategory.UppercaseLetter:       
            case UnicodeCategory.LowercaseLetter:     
            case UnicodeCategory.TitlecaseLetter:                                                  
            case UnicodeCategory.DecimalDigitNumber:                         
                break;
            default:
                throw new Exception("The name '"+name+"' is not a valid identifier.");                
        }
    }
}
' Throws an exception if the specified name does not contain 
' all valid character types.
Public Sub ValidateName(ByVal name As String) Implements INameCreationService.ValidateName
    Dim i As Integer
    For i = 0 To name.Length - 1
        Dim ch As Char = name.Chars(i)
        Dim uc As UnicodeCategory = [Char].GetUnicodeCategory(ch)
        Select Case uc
            Case UnicodeCategory.UppercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.DecimalDigitNumber
            Case Else
                Throw New Exception("The name '" + name + "' is not a valid identifier.")
        End Select
    Next i
End Sub

備註

實作 INameCreationService 中可以有規則來定義有效名稱的參數。 此方法可用於驗證名稱並強制執行這些規則。

此方法與 類似 IsValidName,但若名稱無效,該方法會拋出例外。 這讓實作者能在例外訊息中提供詳細資訊。

適用於