How to convert one type to another using reflection?

前端 未结 3 1488
臣服心动
臣服心动 2021-01-25 03:29

I have a two types that are very similar (i.e. the member names are very similar).

Is there an elegant way to copy one type to another, without having to copy each indi

相关标签:
3条回答
  • 2021-01-25 04:10

    See Copyable: A framework for copying or cloning .NET objects. Its slightly slower (it uses reflection), but it has one advantage: you can alter the source to handle corner cases where the member variables need a little bit of work to convert.

    For example, in the sample source code in the question, member variable "ExpirationDate" is of type "DateTime" in one type, and type "IceDateTime" in the other (you need to convert the date format with the extension method .ToDateTime).

    Here is the source (see the original blog entry for more source):

    // Modification to original source code.
    Type type = instance.GetType();
    
    if (instance.GetType().Name == "DataTable")
    {
        // Added to handle custom type.
        DataTable dt = (DataTable)instance;
        copy = dt.Copy();
    }
    else if (instance.GetType().Name == "DataSet")
    {
        // Added to handle custom type.
        DataSet ds = (DataSet)instance;
        copy = ds.Copy();
    }
    else
    {
        // This is the original source.
        while (type != null)
        {
            foreach (FieldInfo field in type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
            {
                object value = field.GetValue(instance);
                if (visited.ContainsKey(value))
                    field.SetValue(copy, visited[value]);
                else
                    field.SetValue(copy, value.Clone(visited));
            }
            type = type.BaseType;
        }
    }
    return copy;
    
    0 讨论(0)
  • 2021-01-25 04:20

    Use something like AutoMapper for that. It will allow you to simply define that class OptionsEnt should be mapped to FromCsvFile and if they have the properties with same names and types then you won't need to define anything else.

    Otherwise you'll have to iterate by properties.

    0 讨论(0)
  • 2021-01-25 04:23

    Maybe Automapper?

    For example:

    Mapper.CreateMap<FromCsvFile, OptionsEnt >();
    return Mapper.Map<FromCsvFile, OptionsEnt>(fromCsvFile);
    
    0 讨论(0)
提交回复
热议问题