【问题标题】:How to create correct InstanceDescriptor for initializing some properties如何创建正确的 InstanceDescriptor 来初始化某些属性
【发布时间】: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


    【解决方案1】:

    我不知道您要使用什么,但似乎 InstanceDescriptor 不仅采用构造函数,因此您可以执行以下操作:

    public static class FooSerialization
    {
        public static Foo CreateDesignFooInstance()
        {
            return new Foo { Titi = 12, Toto = 42, Tata = 421 };
        }
    }
    

    然后:

    var m = typeof(FooSerialization).GetMethod("CreateDesignFooInstance", 
        BindingFlags.Static | BindingFlags.Public);
    var desc = new InstanceDescriptor(m, null);
    

    【讨论】:

    • 是的,我看到我也可以使用 MemberInfo、PropertyInfo ...即使不太熟悉也可以尝试这样的事情,并且会让你知道
    • Visual Studio 设计器在使用 'Foo' 类时仍然崩溃,无论如何测试了您实现 FooConverter 的解决方案,这很好。这样做public static Foo ConvertToInstance(Foo inst) { return inst.Clone(); }if (destinationType == typeof(InstanceDescriptor) && value is Foo) { var m = typeof(FooConverter).GetMethod("ConvertToInstance", BindingFlags.Static | BindingFlags.Public); return new InstanceDescriptor(m, new object[] { value }); }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-31
    • 1970-01-01
    • 2011-03-15
    • 2021-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多