Converting values between same structure within different namespace. C#

前端 未结 7 1438
情书的邮戳
情书的邮戳 2021-01-13 17:28

I have two similar[all attributes are same.] structures within different namespaces.

Now when i try to copy values between the objects of these structures i am getti

7条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-13 17:48

    An alternative to That Chuck Guy's answer - you could use reflection to get and set the values. No idea what the performance benefits/detriments are.

    public static class EquivelantStructureConversion
        where TInput : class
        where TOutput : new()
    {
        public static TOutput Convert(TInput input)
        {
            var output = new TOutput();
    
            foreach (var inputProperty in input.GetType().GetProperties())
            {
                var outputProperty = output.GetType().GetProperty(inputProperty.Name);
                if (outputProperty != null)
                {
                    var inputValue = inputProperty.GetValue(input, null);
                    outputProperty.SetValue(output, inputValue, null);
                }
            }
    
            return output;
        }
    }
    

    The above example will not throw an exception if the property on the output type doesn't exist, but you could easily add it.

提交回复
热议问题