首页 > 解决方案 > 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"
}

标签: c#

解决方案


您想尝试的实际上是多态性,但它需要虚拟非静态方法。

在您的情况下,您的 B 类应该是这样的:

partial class B : A
{
    public new static string EntityName = "B";

    public static new string GetEntityName()
    {
        return EntityName;
    }
}

推荐阅读