【问题标题】:c# why can't we override static property ? (how can high level classes call base class method with high level data)c# 为什么我们不能覆盖静态属性? (高级类如何调用具有高级数据的基类方法)
【发布时间】:2012-03-22 12:04:28
【问题描述】:

我的问题可能措辞不好,可能是骗人的,但我走了

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

谢谢你

【问题讨论】:

    标签: c# inheritance


    【解决方案1】:

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

    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;
    }
    

    【讨论】:

    • @frenchone 我错过了那部分。您需要创建属性virtual 而不是abstract,在person 类中添加一个实现,并在派生实现中添加一个override
    猜你喜欢
    • 2011-07-09
    • 2011-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-24
    • 2013-12-15
    • 2016-06-14
    • 2012-07-03
    相关资源
    最近更新 更多