使用C#Reflection从字典生成动态对象

Elt*_*sta 6 c# reflection system.reflection

我一直在研究C#中的反射,并且想知道我是否使用带有键的字典 - 值可以创建一个带有变量的对象,其中包含字典中每个键的名称及其值,该词典的关键价值.

我有一个相反的方法,它从字典中提取一个对象,这个字典包含键和类属性及其值,属性的值.

我想知道如果可能的话怎么做.

下面是我的方法,它提取对象的字典:

protected Dictionary<String, String> getObjectProperty(object objeto)
{
    Dictionary<String, String> dictionary = new Dictionary<String, String>();

    Type type = objeto.GetType();
    FieldInfo[] field = type.GetFields();
    PropertyInfo[] myPropertyInfo = type.GetProperties();

    String value = null;

    foreach (var propertyInfo in myPropertyInfo)
    {
        if (propertyInfo.GetIndexParameters().Length == 0)
        {
            value = (string)propertyInfo.GetValue(objeto, null);
            value = value == null ? null : value;
            dictionary.Add(propertyInfo.Name.ToString(), value);
        }
    }

    return dictionary;
}
Run Code Online (Sandbox Code Playgroud)

Pet*_*hie 12

如果你已经有了字典,我会避免反思而只是使用 DynamicObject

例如:

public class DynamicDictionary : DynamicObject
{
    private readonly Dictionary<string, object> dictionary;

    public DynamicDictionary(Dictionary<string, object> dictionary)
    {
        this.dictionary = dictionary;
    }

    public override bool TryGetMember(
        GetMemberBinder binder, out object result)
    {
        return dictionary.TryGetValue(binder.Name, out result);
    }

    public override bool TrySetMember(
        SetMemberBinder binder, object value)
    {
        dictionary[binder.Name] = value;

        return true;
    }
}
Run Code Online (Sandbox Code Playgroud)

可以使用如下:

dynamic x = new DynamicDictionary(
    new Dictionary<string, object> {{"Name", "Peter"}});

Console.WriteLine(x.Name);
Run Code Online (Sandbox Code Playgroud)


Mar*_*fer 3

我不确定这是否是您正在寻找的,但从您的问题来看,我认为您想在运行时从字典中的类型实例化类型,这将通过提供密钥来获取。

如果是这样,那么您可以创建以下类,该类将保存将作为您的键的字符串的键值对,以及将代表将被实例化的值的类型。

class DictionaryActivator
{
    Dictionary<string, Type> Dictionary = new Dictionary<string, Type>();

    public DictionaryActivator()
    {
        Dictionary.Add("MyCar", typeof(Car));
        Dictionary.Add("MyHouse", typeof(House));
        Dictionary.Add("MyFruit", typeof(Fruit));
        Dictionary.Add("MyComputer", typeof(Computer));
    }

    public T GetInstance<T>(string type, params object[] parameters)
    {
        if (parameters.Count() == 0)
        {
            return (T)Activator.CreateInstance(Dictionary[type]);
        }
        else
        {
            return (T)Activator.CreateInstance(Dictionary[type], parameters.ToArray());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

您还可以创建四个测试类来测试此设置。

class House
{
    public int Number = 25;
}

class Car
{
    public double Price = 50000;
}

class Fruit
{
    public string Name = "Apple";
}

class Computer
{
    public string Cpu { get; set; }
    public string Gpu { get; set; }

    public Computer(string cpu, string gpu)
    {
        Cpu = cpu;
        Gpu = gpu;
    }
}
Run Code Online (Sandbox Code Playgroud)

完成此操作后,您可以运行以下代码行以从字典中获取所有类型,实例化它们并将它们转换为适当的类型。您可能会注意到,最后一个计算机示例向您展示了如何向新创建的实例添加多个参数(在本例中为两个参数)并将其作为object类型的实例返回。

最后,您可以将其转换为Computer类型,以便您可以检查构造函数参数实际上是否已转到相应的属性。

class Program
{
    static void Main()
    {
        var source = new DictionaryActivator();

        Console.WriteLine(source.GetInstance<Car>("MyCar").Price);
        Console.WriteLine(source.GetInstance<House>("MyHouse").Number);
        Console.WriteLine(source.GetInstance<Fruit>("MyFruit").Name);

        var computer = source.GetInstance<object>("MyComputer", "Fast CPU", "Fast GPU");

        Console.WriteLine((computer as Computer).Cpu);
        Console.WriteLine((computer as Computer).Gpu);

        Console.Read();
    }
}
Run Code Online (Sandbox Code Playgroud)