我有两个模型:
public class People {
public string Id {get;set;}
public string Name {get;set;}
public DateTime Date {get;set;}
public int Age {get;set;}
}
public class SmallPeople {
public string Id {get;set;}
public string Name {get;set;}
}我要做的是:
SmallPeople smallPeople = someData;
People people = smallPeople as People;但我不能,因为vs显示转换错误。如何修复这个问题?
发布于 2017-02-18 01:44:38
public class People
{
public string Id { get; set; }
public string Name { get; set; }
public DateTime Date { get; set; }
public int Age { get; set; }
}
public class SmallPeople : People
{
}不需要在SmallPeople类中包含Id和Name,因为它们存在于父类中。如果您希望能够在人员数组中使用SmallPeople实例,则需要从人员继承。它将从用户那里获取所有属性。
SmallPeople smallPeople = someData;
People people = smallPeople as People;发布于 2017-02-18 02:19:12
类的名称可以是任何东西,但我会从小到大继承。
public class PersonRecord
{
public string Id { get; set; }
public string Name { get; set; }
}
public class Person : PersonRecord
{
public DateTime Date { get; set; }
public int Age { get; set; }
}这将允许您拥有一个实际上是Person实例的PersonRecord数组。虽然尝试从Person转到PersonRecord可能是一种代码味道,但使用LINQ和myRecordArray.OfType<Person>()可以很容易地完成。
发布于 2017-02-18 02:30:48
我强烈建议您重新考虑您的方法,并使用继承。如果你不想做继承,那么你需要创建一个方法来做你需要的事情。如下所示:
public class People {
public string Id {get;set;}
public string Name {get;set;}
public DateTime? Date {get;set;}
public int? Age {get;set;}
}
public class SmallPeople {
public string Id {get;set;}
public string Name {get;set;}
public People ToPeople()
{
var people = new People();
people.Id = Id;
people.Name = Name;
people.Age = null;
people.Date = null;
return people;
}
}
var small = new SmallPeople();
small.Id="5";
small.Name="My Name";
var people = small.ToPeople();请注意,我将Date和Age设置为可空,以便它们可以包含空值。
https://stackoverflow.com/questions/42304179
复制相似问题