【发布时间】:2017-09-25 15:41:00
【问题描述】:
我有很多类可以制定各种不同的项目。我目前有这样的课程:
public class Item {
public ItemFile file { get; set;}
public ItemCalendar calendar { get; set;}
public ItemWebsite website { get; set;}
}
ItemFile 等是使用实体框架创建的类,并映射到提供与该类型项目相关的信息的数据库表。 item 类只有一个实际实例化的内部属性。
我可以看到项目数量增长到大约 25 个或更多。让视图模型包含 25 个属性,其中 24 个为空,只有一个不为空,我觉得不合适。
我想要一些可以与实体框架一起使用并返回一个只能返回它的实际类型的类。因此,如果我要求更改项目,我会返回 ItemFile 文件和 ItemCalendar 日历。
我尝试过这样的事情:
public class Item
{
public ItemBase item { get; set; }
}
public class ItemBase
{
public Type typeName { get; set; }
public object ItemInstance { get; set; }
public typeName GetInstance()
{
return Convert.ChangeType(ItemInstance, typeName);
}
}
但是我不知道如何将 ItemFile 作为 public typeName 返回是一个错误。
然后我尝试了:
public class Item
{
public ItemBase<ItemFile> item { get; set; }
}
public class ItemBase<T>
{
public T ItemInstance { get; set; }
}
但要让它发挥作用,我必须在项目类的 中硬核 FileItem,这可以追溯到事先知道类型。
有没有办法让它工作?如果它可以与实体框架一起使用,因为我正在从那里撤回类,那么它可以加分。如果实体框架不能正常工作,最糟糕的情况是我可以将其全部提取出来,然后将其转换为回答问题的形式。
如果问题的标题有误,请随时编辑。我不知道怎么问。
tl;dr 版本:我希望能够使用不使用 传入的类型从函数返回多种类型的类。
编辑 1:
我忘了展示我的继承示例。我已经尝试过了,但也遇到了与上述类似的问题。
public class ItemBase
{
public Type typeName { get; set; }
public object ItemInstance { get; set; }
public typeName GetInstance()
{
return Convert.ChangeType(ItemInstance, typeName);
}
}
public class ItemFile : ItemBase
{
public String FileName { get; set; }
}
public class Test
{
public void testFunction()
{
//Made this just so the compiler didn't complain.
ItemFile testFile = new ItemFile();
//I can use a function to get the item base.
ItemBase baseItem = testFile;
//How do I do this? Use a function to get the ItemFile from the instance.
ItemFile finalItem = baseItem.GetInstance();
}
}
【问题讨论】:
-
能展示一下你说的功能吗?
-
您可能想查看继承(正如您的标签所建议的那样),但您的示例代码根本没有这样做。
-
@DavidG 我添加了我的继承示例。
-
你的最后一行只需要
ItemBase finalItem = (ItemBase)baseItem; -
@DavidG 我相信你的意思是 ItemFile 而不是 ItemBase?但是,您提出的问题是我不知道它是 ItemFile 还是 ItemWebsite 等。我想要一个返回正确类型的函数。如果我想每次从数据库中提取它时手动检查并转换它,我相信我可以按照你的建议去做。
标签: c# entity-framework class inheritance