형식 변환기 예제
업데이트: 2007년 11월
이 예제에서는 다른 컨트롤 제작 예제의 Author 개체와 함께 사용되는AuthorConverter라는 형식 변환기를 만드는 방법을 보여 줍니다. ASP.NET에서는 런타임에 형식 변환기를 사용하여 컨트롤 상태 및 뷰 상태에 저장된 개체를 serialize하고 deserialize합니다. AuthorConverter 예제에서는 Author 개체를 String으로 변환하고 String 표현을 Author 개체로 변환합니다. Author 형식에 대한 내용은 서버 컨트롤 속성 예제에서 설명합니다.
TypeConverterAttribute를 사용하여 형식 변환기를 형식(또는 변환기가 정의되는 형식의 속성)과 연결합니다. AuthorConverter를 사용하면 Book 컨트롤에서 Author 속성을 뷰 상태에 저장할 수 있습니다. 사용자 지정 형식은 이 형식에 대해 형식 변환기가 정의되어 있거나 연결된 경우에만 뷰 상태에 저장될 수 있습니다.
AuthorConverter 클래스는 비주얼 디자이너의 속성 브라우저에서 Author 형식의 하위 속성을 편집할 때 확장/축소 사용자 인터페이스를 제공할 수 있도록 ExpandableObjectConverter에서 파생됩니다.
AuthorConverter 클래스에 대한 코드 목록
' AuthorConverter.vb
Imports System
Imports System.ComponentModel
Imports System.ComponentModel.Design.Serialization
Imports System.Globalization
Imports System.Reflection
Namespace Samples.AspNet.VB.Controls
Public Class AuthorConverter
Inherits ExpandableObjectConverter
Public Overrides Function CanConvertFrom( _
ByVal context As ITypeDescriptorContext, _
ByVal sourceType As Type) As Boolean
If sourceType Is GetType(String) Then
Return True
End If
Return MyBase.CanConvertFrom(context, sourceType)
End Function
Public Overrides Function CanConvertTo( _
ByVal context As ITypeDescriptorContext, _
ByVal destinationType As Type) As Boolean
If destinationType Is GetType(String) Then
Return True
End If
Return MyBase.CanConvertTo(context, destinationType)
End Function
Public Overrides Function ConvertFrom( _
ByVal context As ITypeDescriptorContext, _
ByVal culture As CultureInfo, ByVal value As Object) As Object
If value Is Nothing Then
Return New Author()
End If
If (TypeOf value Is String) Then
Dim s As String = CStr(value)
If s.Length = 0 Then
Return New Author()
End If
Dim parts() As String = s.Split(" ".ToCharArray)
' Determine if name is stored as first and last,
' first, middle, and last,
' or is in error.
If (parts.Length < 2) Or (parts.Length > 3) Then
Throw New ArgumentException( _
"Name must have 2 or 3 parts.", "value")
End If
If parts.Length = 2 Then
Return New Author(parts(0), parts(1))
End If
If parts.Length = 3 Then
Return New Author(parts(0), parts(1), parts(2))
End If
End If
Return MyBase.ConvertFrom(context, culture, value)
End Function
Public Overrides Function ConvertTo( _
ByVal context As ITypeDescriptorContext, _
ByVal culture As CultureInfo, ByVal value As Object, _
ByVal destinationType As Type) As Object
If value IsNot Nothing Then
If Not (TypeOf value Is Author) Then
Throw New ArgumentException("Invalid Author", _
"value")
End If
End If
If destinationType Is GetType(String) Then
If value Is Nothing Then
Return String.Empty
End If
Dim auth As Author = CType(value, Author)
If auth.MiddleName <> String.Empty Then
Return String.Format("{0} {1} {2}", _
auth.FirstName, _
auth.MiddleName, _
auth.LastName)
Else
Return String.Format("{0} {1}", _
auth.FirstName, _
auth.LastName)
End If
End If
Return MyBase.ConvertTo(context, culture, value, _
destinationType)
End Function
End Class
End Namespace
// AuthorConverter.cs
using System;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Globalization;
using System.Reflection;
namespace Samples.AspNet.CS.Controls
{
public class AuthorConverter : ExpandableObjectConverter
{
public override bool CanConvertFrom(
ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(string))
{
return true;
}
return base.CanConvertFrom(context, sourceType);
}
public override bool CanConvertTo(
ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(string))
{
return true;
}
return base.CanConvertTo(context, destinationType);
}
public override object ConvertFrom(ITypeDescriptorContext
context, CultureInfo culture, object value)
{
if (value == null)
{
return new Author();
}
if (value is string)
{
string s = (string)value;
if (s.Length == 0)
{
return new Author();
}
string[] parts = s.Split(' ');
// Determine if name is stored as first and
// last; first, middle, and last;
// or is in error.
if ((parts.Length < 2) || (parts.Length > 3))
{
throw new ArgumentException(
"Name must have 2 or 3 parts.", "value");
}
if (parts.Length == 2)
{
return new Author(parts[0], parts[1]);
}
if (parts.Length == 3)
{
return new Author(parts[0], parts[1], parts[2]);
}
}
return base.ConvertFrom(context, culture, value);
}
public override object ConvertTo(
ITypeDescriptorContext context,
CultureInfo culture, object value, Type destinationType)
{
if (value != null)
{
if (!(value is Author))
{
throw new ArgumentException(
"Invalid Author", "value");
}
}
if (destinationType == typeof(string))
{
if (value == null)
{
return String.Empty;
}
Author auth = (Author)value;
if (auth.MiddleName != String.Empty)
{
return String.Format("{0} {1} {2}",
auth.FirstName,
auth.MiddleName,
auth.LastName);
}
else
{
return String.Format("{0} {1}",
auth.FirstName,
auth.LastName);
}
}
return base.ConvertTo(context, culture, value,
destinationType);
}
}
}
코드 설명
AuthorConverter 클래스 구현 예제에서는 Author 인스턴스를 문자열로 변환하거나 반대로 변환하기 위해 수행해야 하는 작업을 보여 줍니다.
특정 형식에서 Author 인스턴스를 만들 수 있는지 여부를 결정하는 CanConvertFrom 메서드를 재정의합니다. 전달된 형식이 String 형식이면 true를 반환합니다.
Author 인스턴스를 특정 형식으로 변환할 수 있는지 여부를 결정하는 CanConvertTo 메서드를 재정의합니다. 전달된 형식이 String 형식이면 true를 반환합니다.
Author 인스턴스의 FirstName, MiddleName 및 LastName 속성이 포함된 문자열 하나를 반환하는 ConvertFrom 메서드를 재정의합니다.
Author 인스턴스의 연결된 FirstName, MiddleName 및 LastName 속성이 포함된 문자열을 구문 분석하는 ConvertTo 메서드를 재정의합니다. 연결된 문자열의 데이터를 사용하여 Author 클래스의 새 인스턴스가 반환됩니다.
예제 빌드 및 사용
서버 컨트롤 속성 예제에 설명되어 있는 Book 컨트롤 및 관련 클래스를 사용하여 AuthorConverter 클래스를 컴파일합니다.
사용자 지정 컨트롤 예제의 컴파일 및 사용에 대한 자세한 내용은 사용자 지정 서버 컨트롤 예제 빌드를 참조하십시오.