简体   繁体   English

将匿名类型转换为类

[英]Convert anonymous type to class

I got an anonymous type inside a List anBook:我在 List anBook 中有一个匿名类型:

var anBook=new []{

new {Code=10, Book ="Harry Potter"},
new {Code=11, Book="James Bond"}
};

Is to possible to convert it to a List with the following definition of clearBook:是否可以将其转换为具有以下 clearBook 定义的列表:

public class ClearBook
{
  int Code;
  string Book; 
}

by using direct conversion, ie, without looping through anBook?通过使用直接转换,即不循环遍历 anBook?

Well, you could use:那么,你可以使用:

var list = anBook.Select(x => new ClearBook {
               Code = x.Code, Book = x.Book}).ToList();

but no, there is no direct conversion support.但不,没有直接转换支持。 Obviously you'll need to add accessors, etc. (don't make the fields public) - I'd guess:显然,您需要添加访问器等(不要公开字段)-我猜:

public int Code { get; set; }
public string Book { get; set; }

Of course, the other option is to start with the data how you want it:当然,另一种选择是从您想要的数据开始:

var list = new List<ClearBook> {
    new ClearBook { Code=10, Book="Harry Potter" },
    new ClearBook { Code=11, Book="James Bond" }
};

There are also things you could do to map the data with reflection (perhaps using an Expression to compile and cache the strategy), but it probably isn't worth it.您还可以通过反射来映射数据(也许使用Expression来编译和缓存策略),但这可能不值得。

As Marc says, it can be done with reflection and expression trees... and as luck would have it, there's a class in MiscUtil which does exactly that.正如 Marc 所说,它可以通过反射树和表达式树来完成……幸运的是, MiscUtil 中有一个类可以做到这一点。 However, looking at your question more closely it sounds like you want to apply this conversion to a collection (array, list or whatever) without looping .但是,更仔细地查看您的问题,听起来您想将此转换应用于集合(数组、列表或其他任何内容)而不使用 looping That can't possibly work.那不可能行得通。 You're converting from one type to another - it's not like you can use a reference to the anonymous type as if it's a reference to ClearBook.您正在从一种类型转换为另一种类型 - 您不能像使用对 ClearBook 的引用一样使用对匿名类型的引用。

To give an example of how the PropertyCopy class works though, you'd just need:要举例说明 PropertyCopy 类的工作方式,您只需要:

var books = anBook.Select(book => PropertyCopy<ClearBook>.CopyFrom(book))
                                 .ToList();

What about these extension?这些扩展呢? simple call the .ToNonAnonymousList on your anonymous type..简单地调用匿名类型的 .ToNonAnonymousList ..

public static object ToNonAnonymousList<T>(this List<T> list, Type t)
    {
        //define system Type representing List of objects of T type:
        Type genericType = typeof (List<>).MakeGenericType(t);

        //create an object instance of defined type:
        object l = Activator.CreateInstance(genericType);

        //get method Add from from the list:
        MethodInfo addMethod = l.GetType().GetMethod("Add");

        //loop through the calling list:
        foreach (T item in list)
        {
            //convert each object of the list into T object by calling extension ToType<T>()
            //Add this object to newly created list:
            addMethod.Invoke(l, new[] {item.ToType(t)});
        }
        //return List of T objects:
        return l;
    }
    public static object ToType<T>(this object obj, T type)
    {
        //create instance of T type object:
        object tmp = Activator.CreateInstance(Type.GetType(type.ToString()));

        //loop through the properties of the object you want to covert:          
        foreach (PropertyInfo pi in obj.GetType().GetProperties())
        {
            try
            {
                //get the value of property and try to assign it to the property of T type object:
                tmp.GetType().GetProperty(pi.Name).SetValue(tmp, pi.GetValue(obj, null), null);
            }
            catch (Exception ex)
            {
                Logging.Log.Error(ex);
            }
        }
        //return the T type object:         
        return tmp;
    }

The simplest way to do it could just be to use some type of serialization method.最简单的方法就是使用某种类型的序列化方法。

something like along these lines类似这样的事情

class ClearBook
{
   public int Code { get; set; }
   public string Book { get; set; }
}

ClearBook[] newList = JsonSerializer.Deserialize<ClearBook[]>(JsonSerializer.Serialize(anBook));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM