c# - C#:具有返回派生类成员的静态基类方法
问题描述
我正在尝试在基类的静态方法中访问派生类的静态成员。那可能吗?派生类必须是部分的。另一个部分类是自动生成的 Linq2SQL 类。
GetEntityName(ID)方法应该是静态的,因为我还想在不实例化该类的对象的情况下访问该方法。并且该方法必须能够访问EntityName为什么该成员必须是静态的。
更新
我更新了课程以阐明所需的功能:
abstract class A
{
public static string EntityName = "A";
public int ID { get; set; }
public string GetEntityName()
{
return GetEntityName(ID);
}
public static string GetEntityName(int ID)
{
return EntityName + " with ID " + ID;
}
}
// Linq2Sql-Class
partial class B
{
public B()
{
}
}
// Customized Linq2Sql class
partial class B : A
{
public new static string EntityName = "B";
}
static void Main(string[] args)
{
// static method uses same logic as in the non-static method
var result = B.GetEntityName(5); // <-- Should return "B with ID 5" but returns "A with ID 5"
var BTest = new B
{
ID = 6
};
var result2 = BTest.GetEntityName(); // <-- Should return "B with ID 6" but returns "A with ID 6"
}
解决方案
您想尝试的实际上是多态性,但它需要虚拟非静态方法。
在您的情况下,您的 B 类应该是这样的:
partial class B : A
{
public new static string EntityName = "B";
public static new string GetEntityName()
{
return EntityName;
}
}
推荐阅读
- django - 包含在 urlpatterns 和 404 中
- mysql - Mysql.connector.errors.DatabaseError: 2014 (HY000): 命令不同步;你现在不能运行这个命令
- shacl - 以特定类的所有对象为目标,SHACL 中的指定实例除外
- python - 如何将数据集传递给函数而不将其作为 Python 函数中的参数传递
- java - Spring Boot - 约束验证器 @Autowired 字段 null
- r - 在R中按组将函数应用于多个变量
- character-encoding - 命令提示符更改粘贴文本中的字符
- mysql - Where 子句订单性能,限制索引使用
- java - assertThat:如何反转 containsString
- sharepoint-2013 - 无法将所有用户保存到 SharePoint 列表中