开发者

How to create correct InstanceDescriptor for initializing some properties

开发者 https://www.devze.com 2023-03-22 08:44 出处:网络
Lets say I have a class like this: public class Foo { public Foo {} public int Titi { get; set; } public int Toto { get; set; }

Lets say I have a class like this:

public class Foo
{
    public Foo {}

    public int Titi { get; set; }
    public int Toto { get; set; }
    public int Tata { get; set; }
}

I can initialize a new instance like this:

var inst = new Foo { Titi = 12, Toto = 42, Tata = 421 };

But how can I create correct instance descriptor that performs same initialization as above?

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开发者_StackOverflow
            var ctor = typeof(Foo).GetConstructor(Type.EmptyTypes); 

            return new InstanceDescriptor(ctor, null);
         }

         // ...
    }
}

NB1: I'm asking this because I want to create a TypeConverter for 'Foo' class and need to provide convertion to 'InstanceDescriptor'

NB2: Yes, I can add a constructor to Foo class that takes 3 arguments, but would like to avoid this and also would like to know which "construction description" corresponds to above sample.


I don't know what you are trying to use but it seem that InstanceDescriptor don't only take constructors so you could do something like this :

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

And then :

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

精彩评论

暂无评论...
验证码 换一张
取 消