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

我的问题可能没有很好地表达,它可能是一个骗局,但我在这里

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

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

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

我得到了一些低级别的东西(没有在那里找到),它位于基类中(因为我不想复制),我希望inheritance的类用herited类的上下文调用基类方法

我想要man。[inheritance] 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; } 

你为什么不能? 因为.net设计者认为将该工具添加到框架中比将其设置更麻烦。

至于处理你的设计,有很多方法可以让它更好……

一个是拥有一个静态帮助器类,将sql作为静态字符串放入其中并添加一个静态方法来返回它,然后从Person,Man Woman等调用它。在Person中放入一个枚举,在helper中放一个静态GetSql上课并完成工作。

哦,并理清你的接受率,否则人们不会帮助你。