擴展屬性和字符串轉換
圖
不過
在
比如
[TypeConverter(typeof(PersonConverter))]
public class Person
{
private string firstName =
private string lastName =
private intage =
public int Age
{
get
{
return age;
}
set
{
age = value;
}
}
public string FirstName
{
get
{
return firstName;
}
set
{
this
}
}
public string LastName
{
get
{
return lastName;
}
set
{
this
}
}
}
我們注意到Person類被指定了TypeConverterAttribute特性
internal class PersonConverter : TypeConverter
{
public override PropertyDescriptorCollection
GetProperties(ITypeDescriptorContext context
object value
Attribute[] filter)
{
return TypeDescriptor
}
public override bool GetPropertiesSupported(
ITypeDescriptorContext context)
{
return true;
}
}
在通常情況下
internal class PersonConverter : ExpandableObjectConverter
{
public override bool CanConvertFrom(
ITypeDescriptorContext context
{
if (t == typeof(string))
{
return true;
}
return base
}
public override object ConvertFrom(
ITypeDescriptorContext context
CultureInfo info
object value)
{
if (value is string)
{
try
{
string s = (string) value;
// parse the format
//
int comma = s
if (comma !=
{
// now that we have the comma
// the last name
string last = s
int paren = s
if (paren !=
{
// pick up the first name
string first = s
// get the age
int age = Int
s
s
Person p = new Person();
p
p
p
return p;
}
}
}
catch {}
// if we got this far
// couldn
//
throw new ArgumentException(
}
return base
}
public override object ConvertTo(
ITypeDescriptorContext context
CultureInfo culture
object value
Type destType)
{
if (destType == typeof(string) && value is Person)
{
Person p = (Person)value;
// simply build the string as
return p
p
}
return base
}
}
現在看看我們的Person屬性在指定了PersonConverter類型轉換器之後
圖
要使用上面的代碼
private Person p = new Person();
public Person Person
{
get
{
return p;
}
set
{
this
}
}
From:http://tw.wingwit.com/Article/program/net/201311/12805.html