2016-09-17 32 views
0

是否可以在以下示例中覆盖Filter2类中的BaseFilter.Type值?覆盖第二个子类中的基类值

void Main() 
{ 
    BaseFilter abc = new Filter2(); 
    Console.WriteLine(abc.Type); 

    Filter1 d = new Filter2(); 
    Console.WriteLine(d.Type); 

    Filter2 e = new Filter2(); 
    Console.WriteLine(e.Type); 
} 

// Define other methods and classes here 

public class BaseFilter 
{ 
    public virtual string Type { get { return "ABC"; } } 
} 

public class Filter1 : BaseFilter 
{ 
    public new virtual string Type { get { return "DEF"; } } 
} 

public class Filter2 : Filter1 
{ 
    public override string Type { get { return "X"; } } 
} 

在某种意义上,从上面的例子中,我想看看,如果“abc.Type”可以返回值“X”。但是,我不想从Filter1类中删除“新”关键字。

所以,这里是最后的期望值

  1. 过滤器1类不应该覆盖从BaseFilter类值。
  2. 但是,Filter2类应该覆盖BaseFilter和Filter1中的值。

OOPS语言可以吗?

+1

用'new'关键字遮蔽,几乎总是一个坏主意。 – Enigmativity

回答

1

一般来说,这是一个坏主意。我从java的角度回答,我们没有那种getter的好主意。

但重点是:良好的OO设计中的多态性约为行为,而不是约字段

含义:您不希望该子类必须更改父项字段的内容才能做到这一点。你想要的事情是相反的,如Open/Closed principle所述!

+0

Java,这是C#...?你认为这是一个糟糕的主意,我认为仍然存在。 – jdphenix

0

目前尚不清楚为什么你需要这种行为。你能解释一下吗?

我不确定,但是当我读到你的问题时,你将违反所有关于OO和多态的好处:-)。

下面,但是我建议使用的过滤器2的BaseFilter.Type接口的方法,但它不是一个良好的设计和只是为了“好玩”:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace SO39543589 
{ 

    public interface ISecondTyper 
    { 
    string Type { get; } 
    } 

    // Define other methods and classes here 

    public class BaseFilter 
    { 
    public virtual string Type { get { return "ABC"; } } 
    } 

    public class Filter1 : BaseFilter 
    { 
    public new virtual string Type { get { return "DEF"; } } 
    } 

    public class Filter2 : Filter1, ISecondTyper 
    { 
    string ISecondTyper.Type 
    { 
     get 
     { 
     return (this as BaseFilter).Type; 
     } 
    } 
    public override string Type { get { return "X"; } } 
    } 

    class Program 
    { 
    static void Main() 
    { 
     BaseFilter abc = new Filter2(); 
     Console.WriteLine(abc.Type); 

     Filter1 d = new Filter2(); 
     Console.WriteLine(d.Type); 

     Filter2 e = new Filter2(); 
     Console.WriteLine(e.Type); 

     ISecondTyper st = e; 
     Console.WriteLine(st.Type); 

     Console.WriteLine("END"); 
     Console.ReadLine(); 
    } 
    } 
}