加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何创建正确的InstanceDescriptor以初始化某些属性

发布时间:2020-12-15 17:18:39 所属栏目:百科 来源:网络整理
导读:可以说我有这样一个类: 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 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个参数的构造函数,但是想避免这种情况,并且想知道哪个“构造描述”对应于上面的示例.

解决方法

我不知道你想要使用什么,但似乎InstanceDescriptor不仅采用构造函数,所以你可以做这样的事情:

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

然后 :

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读