微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C#反射获取对象列表

如何解决C#反射获取对象列表

我从我制作的数组对象中获取对象时遇到问题。似乎没有获取对象,请参见下面的代码

产品型号

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并根据字典设置其属性的函数。

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

Vec

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。