c# 为什么我们不能覆盖静态属性? (高级类如何使用高级数据调用基类方法)

标签 c# inheritance

我的问题可能措辞不当,可能是个骗局,但我开始了

class person {
    protected static string request = "select * from person where gender in ('male','female')";
    public string sharedmethod()
    {
        return "the request is" + request;
    }
}

class man:person
{
    override protected static string request = "select person.*,man.* from person,men where mytype in ('male') ";
    DateTime dateOfFirstCar;
}

class woman:person
{
    override protected static string request = "select person.*,woman.* from person,women where mytype in ('female') ";
    DateTime dateOfFirstITBAG;
}

class Program
{
    static void Main(string[] args)
    {
        if (new person().sharedmethod() == new man().sharedmethod())
            Console.Write("too bad query is the same in base and dervide class");
    }
}

人就是人
女人是一个人
Person,man,woman 存在于我的数据库中,但需要不同的查询

我不想重复这些查询,所以我认为将它们存储在每个类的静态属性中是个好主意。

我在基类中得到了一些低级的东西(那里没有图)(因为我不想重复),我希望继承类在继承类的上下文中调用基类方法

我希望 man.[inherited]somemethod() 执行 person.somemethod() 但变量来自 man

谢谢

最佳答案

添加一个覆盖静态字符串的非静态属性,并改为引用该属性:

class person {
    private const string request = "select * from person where gender in ('male','female')";
    protected virtual string Request {get {return request;}}
    public string sharedmethod() {
        return "the request is" + Request;
    }
}

class man:person {
    private const string request = "select person.*,man.* from person,men where mytype in ('male') ";
    protected override string Request {get {return request;}}
    DateTime dateOfFirstCar;
}

class woman:person {
    private const string request = "select person.*,woman.* from person,women where mytype in ('female') ";
    protected override string Request {get {return request;}}
    DateTime dateOfFirstITBAG;
}

关于c# 为什么我们不能覆盖静态属性? (高级类如何使用高级数据调用基类方法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9821903/

相关文章:

c# - 当应用程序是默认处理程序时,NLog 将日志文件写入不正确的目录

c++ - 继承 - 为什么这是非法的?

C++继承问题

C++ 使用 "friend"

c++ - 为什么在 C++ 中捕获时派生异常类型会丢失?

c# - 如何将多个文本框中的文本更改事件连接到单个方法(C#)?

c# - lambda 表达式 C#

c# - 在 .NET Core 3.0 中加载 exe 时出现错误的 IL 格式

c# - 如何将 Roslyn 脚本提交用作其他 Roslyn 编译中的程序集

java - Reflection api - 查找子类类型