【发布时间】:2019-04-22 05:34:57
【问题描述】:
我正在构建将与 SQLite 一起使用的应用程序,我现在要做的是为每个实体获取表创建字符串,这些字符串应该使用如下代码存储:
table_creation_string1 = Book.GetTableCreationString();
table_creation_string2 = Scroll.GetTableCreationString();
这将允许我使用自定义属性创建新实体以存储表名和字段名,从而做最少的工作。
这是我的设置示例:
[System.AttributeUsage(System.AttributeTargets.Class)]
public class DBItemAttribute : System.Attribute
{
public string TableName;
public DBItemAttribute(string table_name)
{
TableName = table_name;
}
}
internal abstract class DBItem
{
...
}
[DBItemAttribute("book_table")]
internal class Book : DBItem
{
...
}
[DBItemAttribute("scroll_table")]
internal class Scroll : DBItem
{
...
}
我面临的问题是,如果不构造对象,我无法获取 Book 和 Scroll 类的属性值。换句话说-像这样使用smth:
string table1 = Scroll.GetTableName();
string table2 = Book.GetTableName();
下一个值输出
"scroll_table"
"book_table"
因此,我正在为此寻找最佳解决方案或一些好的替代方案。
我已经了解到基类中的静态方法对此不起作用,因为似乎无法获取派生类信息调用基类中定义的静态方法。
更新: 像
这样的代码table_creation_string1 = new Book().GetTableCreationString();
确实有效,但我想知道是否可以按照我上面描述的方式完成。
【问题讨论】:
-
应该可以在不构造对象的情况下获取属性信息。属性是类型的属性。看看这个:stackoverflow.com/questions/2656189/…
-
还有你为什么要重新发明轮子,假设已经有库处理数据库创建/处理:docs.microsoft.com/en-us/ef/ef6/modeling/code-first/workflows/…
-
你是对的,我可以在不构造对象的情况下获得 t,但在这种情况下,我需要在我使用的每个类中编写实际上相同的方法,并且有几十个。感谢您的链接,我会尽快检查它
标签: c# inheritance static attributes