C# using reflection to create a struct

前端 未结 3 1613
时光取名叫无心
时光取名叫无心 2020-12-20 11:57

I am currently writing some code to save general objects to XML using reflection in c#.

The problem is when reading the XML back in some of the objects are structs a

3条回答
  •  旧巷少年郎
    2020-12-20 12:38

    If the values are structs, they're likely to be immutable - so you don't want to call a parameterless constructor, but the one which takes the appropriate values as constructor arguments.

    If the structs aren't immutable, then run away from them as fast as possible, if you can... but if you absolutely have to do this, then use Activator.CreateInstance(SomeClass). You'll have to be very careful when you use reflection to set properties or fields on the value type though - without that care, you'll end up creating a copy, changing the value on that copy, and then throwing it away. I suspect that if you work with a boxed version throughout, you'll be okay:

    using System;
    
    // Mutable structs - just say no...
    public struct Foo
    {
        public string Text { get; set; }
    }
    
    public class Test
    {
        static void Main()
        {
            Type type = typeof(Foo);
    
            object value = Activator.CreateInstance(type);
            var property = type.GetProperty("Text");
            property.SetValue(value, "hello", null);
    
            Foo foo = (Foo) value;
            Console.WriteLine(foo.Text);
        }
    }
    

提交回复
热议问题