使用反射来创建一个结构C# [英] C# using reflection to create a struct

查看:152
本文介绍了使用反射来创建一个结构C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在写一些代码,以节省使用C#反射XML一般对象。

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

问题是在一些对象读取XML时,后面是结构我不能工作,如何初始化结构。针对一类,我可以使用

The problem is when reading the XML back in some of the objects are structs and I can't work out how to initialise the struct. For a class I can use

ConstructorInfo constructor = SomeClass.GetConstructor(Type.EmptyTypes);



然而,对于一个结构,有没有构造函数不带任何参数,因此上面的代码设置构造函数空值。我也试过

however, for a struct, there is no constructor which takes no parameters so the above code sets constructor to null. I also tried

SomeStruct.TypeInitializer.Invoke(null)

但是这将引发memberaccessexception。谷歌没有给出有前途命中。任何帮助,将不胜感激。

but this throws a memberaccessexception. Google gives no promising hits. Any help would be appreciated.

推荐答案

如果值是结构,它们的可能的是一成不变的 - 所以你不想调用参数的构造函数,但是这需要相应的值作为构造函数参数之一

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.

如果该结构的的不可变的,然后运行远离他们尽可能快的,如果可以的话......但如果​​你绝对有无的做到这一点,然后用 Activator.CreateInstance( SomeClass的)。你必须要非常小心,当您使用反射来,虽然设定的值类型的属性或字段 - 没有这种照顾,你最终会创建一个副本,在该副本更改值,然后把它扔了。

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);
    }
}

这篇关于使用反射来创建一个结构C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆