5

出于听觉原因,我使用 binaryformatter 将业务方法的参数序列化到数据库中。

问题是,当参数是通用列表时,我找不到转换反序列化对象的方法,因为我不知道类型,或者如果我知道类型,我不知道如何将对象转换为运行。

任何人都知道如何在运行时动态地转换包含通用列表的对象吗?

我需要这样做,因为我需要在属性网格中显示反序列化数据:

object objArg = bformatter.Deserialize(memStr);

//If the type is a clr type (int, string, etc)
if (objArg.GetType().Module.Name == "mscorlib.dll")
{                 
    //If the type is a generic type (List<>, etc) 
    //(I'm only use List for these cases)
    if (objArg.GetType().IsGenericType)
    {
         // here is the problem
         pgArgsIn.SelectedObject = new { Value = objArg};                    

         //In the previous line I need to do something like... 
         //new { Value = (List<objArg.GetYpe()>) objArg};
     }
     else
     {
         pgArgsIn.SelectedObject = new { Value = objArg.ToString() };                    
     }
}
else
{
    //An entity object
    pgArgsIn.SelectedObject = objArg;                
}
4

2 回答 2

3

有了BinaryFormatter不需要知道类型;元数据包含在流中(使其更大,但是嘿!)。但是,除非您知道类型,否则您不能强制转换。通常在这种情况下,您必须使用常见的已知接口(非泛型IList等)和反射。而且很多。

我也想不出知道要在 a 中显示的类型的巨大要求PropertyGrid- 因为它接受object,所以只给它BinaryFormatter提供的东西。您在那里看到的具体问题是什么?同样,您可能想要检查IList(non-generic) - 但不值得担心IList<T>,因为这不是PropertyGrid检查的内容!

你当然可以找到T想要的(像这样) - 并使用MakeGenericType()Activator.CreateInstance- 不漂亮。


好的; 这是一种使用自定义描述符的方法,它不涉及对对象或列表类型的任何了解;如果你真的想要,可以将列表项直接扩展到属性中,所以在这个例子中你会看到 2 个假属性(“Fred”和“Wilma”)——不过,这是额外的工作;-p

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;

class Person
{
    public string Name { get; set; }
    public DateTime DateOfBirth { get; set; }

    public override string ToString() {
        return Name;
    }
}

static class Program
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Person fred = new Person();
        fred.Name = "Fred";
        fred.DateOfBirth = DateTime.Today.AddYears(-23);
        Person wilma = new Person();
        wilma.Name = "Wilma";
        wilma.DateOfBirth = DateTime.Today.AddYears(-20);

        ShowUnknownObject(fred, "Single object");
        List<Person> list = new List<Person>();
        list.Add(fred);
        list.Add(wilma);
        ShowUnknownObject(list, "List");
    }
    static void ShowUnknownObject(object obj, string caption)
    {
        using(Form form = new Form())
        using (PropertyGrid grid = new PropertyGrid())
        {
            form.Text = caption;
            grid.Dock = DockStyle.Fill;
            form.Controls.Add(grid);
            grid.SelectedObject = ListWrapper.Wrap(obj);
            Application.Run(form);
        }
    }
}

[TypeConverter(typeof(ListWrapperConverter))]
public class ListWrapper
{
    public static object Wrap(object obj)
    {
        IListSource ls = obj as IListSource;
        if (ls != null) obj = ls.GetList(); // list expansions

        IList list = obj as IList;
        return list == null ? obj : new ListWrapper(list);
    }
    private readonly IList list;
    private ListWrapper(IList list)
    {
        if (list == null) throw new ArgumentNullException("list");
        this.list = list;
    }
    internal class ListWrapperConverter : TypeConverter
    {
        public override bool GetPropertiesSupported(ITypeDescriptorContext context)
        {
            return true;
        }
        public override PropertyDescriptorCollection GetProperties(
            ITypeDescriptorContext context, object value, Attribute[] attributes) {
            return new PropertyDescriptorCollection(
                new PropertyDescriptor[] { new ListWrapperDescriptor(value as ListWrapper) });
        }
    }
    internal class ListWrapperDescriptor : PropertyDescriptor {
        private readonly ListWrapper wrapper;
        internal ListWrapperDescriptor(ListWrapper wrapper) : base("Wrapper", null)
        {
            if (wrapper == null) throw new ArgumentNullException("wrapper");
            this.wrapper = wrapper;
        }
        public override bool ShouldSerializeValue(object component) { return false; }
        public override void ResetValue(object component) {
            throw new NotSupportedException();
        }
        public override bool CanResetValue(object component) { return false; }
        public override bool IsReadOnly {get {return true;}}
        public override void SetValue(object component, object value) {
            throw new NotSupportedException();
        }
        public override object GetValue(object component) {
            return ((ListWrapper)component).list;
        }
        public override Type ComponentType {
            get { return typeof(ListWrapper); }
        }
        public override Type PropertyType {
            get { return wrapper.list.GetType(); }
        }
        public override string DisplayName {
            get {
                IList list = wrapper.list;
                if (list.Count == 0) return "Empty list";

                return "List of " + list.Count
                    + " " + list[0].GetType().Name;
            }
        }
    }
}
于 2009-11-26T17:31:07.710 回答
2

如果您使用的序列化程序不保留类型 - 至少,您必须将类型T与数据一起存储,并使用它来反射地创建通用列表:

//during storage:
Type elementType = myList.GetType().GetGenericTypeDefinition().GetGenericArguments[0];
string typeNameToSave = elementType.FullName;

//during retrieval
string typeNameFromDatabase = GetTypeNameFromDB();
Type elementType = Type.GetType(typeNameFromDatabase);
Type listType = typeof(List<>).MakeGenericType(new Type[] { elementType });

现在你有了listType,这正是List<T>你使用的(比如List<Foo>)。您可以将该类型传递到您的反序列化例程中。

于 2009-11-26T17:25:03.100 回答