繁体   English   中英

C#反射获取对象列表

[英]C# Reflection Get List of Object

从我创建的数组对象中获取对象时遇到问题。 似乎它没有获取对象,请参阅下面的代码:

产品型号

public class Product
{
    public string Id { get; set; }
    public List<ExcelName> ShortDesc { get; set; } // I want to get the object from here
}

简短描述模型

// get this object and the properties inside it.
public class ExcelName
{
    public string Name { get; set; }
    public string Language { get; set; }
}

我的代码

private static T SetValue<T>(Dictionary<string, object> objectValues)
{
    var type = typeof(T);
    var objInstance = Activator.CreateInstance(type);
    if (!type.IsClass) return default;
    foreach (var value in objectValues)
    {
         if (value.Key.Contains(":Language="))
         {
             var propName = value.Key.Split(':')[0];
             // propName is ShortDesc object
             var propInfo = type.GetProperties(BindingFlags.Public | BindingFlags.Instance).FirstOrDefault(e => e.Name.ToLower() == propName.ToLower().Replace(" ", ""));
             if (propInfo == null) continue;
             if (propInfo.PropertyType.IsGenericType)
             {
                 // I want to get the type and properties from T generic using reflection instead static
                 var name = typeof(ExcelName);
                 var excelNameObjectInstance = Activator.CreateInstance(name);
                 foreach (var propertyInfo in name.GetProperties())
                 {
                     propertyInfo.SetValue(excelNameObjectInstance, value.Value, null);
                 }

                 // add excelNameObjectInstance object to the list in ShortDesc
              }
         }
    }

}

如何从ShortDesc列表中获取对象以获取ExcelName对象。

我不太确定您要做什么,但似乎您想要一个函数来实例化 T 并根据字典设置其属性。

你的一半代码对我来说没有意义,但我的猜测是正确的,你不需要比这更复杂的东西:

private static T SetValue<T>(Dictionary<string, object> objectValues) where T : class, new()
{
    var type = typeof(T);
    var instance = new T();
    foreach (var entry in objectValues)
    {
        type.GetProperty(entry.Key).SetValue(instance, entry.Value);
    }
    return instance;
}

如果您不希望键与属性名称完全匹配,则可以引入规范化函数:

private static string Normalize(string input)
{
    return input.ToLower().Replace(" ", "");
}

private static T SetValue<T>(Dictionary<string, object> objectValues) where T : class, new()
{
    var type = typeof(T);
    var instance = new T();
    foreach (var entry in objectValues)
    {
        var prop = type.GetProperties(BindingFlags.Instance | BindingFlags.Public)
            .First( x => Normalize(x.Name) == Normalize(entry.Key) );
        prop.SetValue(instance, entry.Value);
    }
    return instance;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM