【发布时间】:2016-01-23 21:27:33
【问题描述】:
所以这是我的情况。我有 2 个课程,TmdbTvShow 和 TvShow。
TmdbTvShow 是一个填充了我从外部来源获得的数据的类。现在我想创建某种映射器来将其映射到我自己的类 TvShow。
类电视节目:
[MovieMap("TmdbTvShow")]
public class TvShow
{
public int ID { get; set; }
[MovieMapProperty("ID")]
public int TmdbID { get; set; }
[MovieMapProperty("Name")]
public string Name { get; set; }
[MovieMapProperty("OriginalName")]
public string OriginalName { get; set; }
[MovieMapProperty("Overview")]
public string Summary { get; set; }
[MovieMapProperty("FirstAirDate")]
public DateTime FirstAirDate { get; set; }
[MovieMapProperty("LastAirDate")]
public DateTime LastAirDate { get; set; }
[MovieMapProperty("Genres")]
public IEnumerable<Genre> Genres { get; set; }
[MovieMapProperty("InProduction")]
public bool Running { get; set; }
}
映射器类:
public class MovieMapper
{
public MovieMapper()
{
}
public T Map<T>(object input) where T : new()
{
T obj = new T();
MovieMapAttribute[] classAttributes = (MovieMapAttribute[])obj.GetType().GetCustomAttributes(typeof(MovieMapAttribute), false);
if (classAttributes != null && classAttributes[0].ClassName.Equals(input.GetType().Name))
{
Dictionary<string, MovieMapPropertyAttribute> propAtts = new Dictionary<string, MovieMapPropertyAttribute>();
foreach (PropertyInfo prop in obj.GetType().GetProperties())
{
MovieMapPropertyAttribute[] mma = (MovieMapPropertyAttribute[])prop.GetCustomAttributes(typeof(MovieMapPropertyAttribute), false);
// Attribute found
if (mma.Length > 0)
{
// Get attribute
MovieMapPropertyAttribute mmp = mma[0];
// Get value
var value = input.GetType().GetProperty(mmp.PropertyName).GetValue(input, null);
// Is property a dateTime
if (typeof(DateTime).IsAssignableFrom(prop.PropertyType))
{
// Set value to object
obj.GetType().GetProperty(prop.Name).SetValue(obj, Convert.ToDateTime(value), null);
}
else if (typeof(IEnumerable).IsAssignableFrom(prop.PropertyType) && prop.PropertyType != typeof(string))
{
}
else if (typeof(Boolean).IsAssignableFrom(prop.PropertyType))
{
// Set value to object
obj.GetType().GetProperty(prop.Name).SetValue(obj, Convert.ToBoolean(value), null);
}
else
{
// Set value to object
obj.GetType().GetProperty(prop.Name).SetValue(obj, value, null);
}
}
}
}
else
throw new Exception("Wrong object");
return obj;
}
}
所以 atm 我得到了它的工作,像 int、string、booleans 和 DateTime 这样的东西被映射到我的对象。
但正如您所见,我的 TvShow 课程中有一个 IEnumerable。这是此电视节目的流派集合。
我有点不知道如何使 2 个 IEnumerables 相互映射。 如果我像字符串一样执行此操作,则会收到此错误:
a object of type System.Collections.Generic.List can not be converted to the type System.Collections.Generic.IEnumerable
也许有人可以让我在如何处理这个问题上朝着正确的方向前进?
干杯
【问题讨论】:
标签: c# generics mapping ienumerable