【发布时间】:2011-07-21 08:31:48
【问题描述】:
假设我有这样的课程:
public class Foo
{
public Foo {}
public int Titi { get; set; }
public int Toto { get; set; }
public int Tata { get; set; }
}
我可以像这样初始化一个新实例:
var inst = new Foo { Titi = 12, Toto = 42, Tata = 421 };
但是如何创建正确的实例描述符来执行与上述相同的初始化?
public class FooConverter : TypeConverter
{
// ...
public override object ConvertTo(ITypeDescriptorContext context,
CultureInfo culture,
object value,
Type destinationType)
{
if (destinationType == typeof(InstanceDescriptor) && value is Foo)
{
// Incorrect example because properties wont
// be initialized to 12, 42 and 421
var ctor = typeof(Foo).GetConstructor(Type.EmptyTypes);
return new InstanceDescriptor(ctor, null);
}
// ...
}
}
NB1:我问这个是因为我想为“Foo”类创建一个 TypeConverter,并且需要提供到“InstanceDescriptor”的转换
NB2:是的,我可以向 Foo 类添加一个带有 3 个参数的构造函数,但想避免这种情况,也想知道哪个“构造描述”对应于上述示例。
【问题讨论】:
标签: c# .net typeconverter