2014-01-28 132 views
1

添加新的类成员如何做这样的事情(不创建中级班): 覆盖和C#

abstract class A 
{ 
    public abstract string Text { get; } 
} 

class B : A 
{ 
    string text = ""; 
    public override string Text 
    { 
     get { return text; } 
    } 

    new public string Text 
    { 
     get { return (this as A).Text; } 
     set { text = value; } 
    } 
} 

编译器说:类型“B”已经包含了“文本”的定义。

澄清:如何做到这一点(但无类“中级”):

abstract class A 
{ 
    public abstract string Text { get; } 
} 

class Intermediate : A 
{ 

    protected string text = ""; 

    public override string Text 
    { 
     get { return text; } 
    } 

} 

class B : Intermediate 
{ 
    new public string Text 
    { 
     get { return (this as A).Text; } 
     set { text = value; } 
    } 
} 
+0

为什么想要这样做吗? – Davecz

+0

我想在A(和子类)中读取属性并在B(和子类)中读取/写入属性 – Michael

回答

1

你是在同一个班两次定义属性的文本。您正在覆盖它并使用关键字new。删除文本的第二个副本。

class B : A 
{ 
    private string text; 
    public override string Text{ get; set;}  

} 
+0

Compiller说:无法覆盖,因为'A.Text'没有可覆盖的set访问器 – Michael

4

如果您希望该属性在派生类中是可读写的,那么这是不可能的。
该属性是PropertyType get_PropertyName()(当属性可读时)和void set_PropertyName(PropertyType value)(当属性是可写的)方法时的语法糖。这条线:

public abstract string Text { get; } 

表示:

public abstract string get_Text(); 

而且这样的:

public override string Text{ get; set;} 

表示:

public override string get_Text() 
{ 
    // ... 
} 

public override void set_Text(string value) 
{ 
    // ... 
} 

由于在基类中没有抽象set_Text方法,你可以不会覆盖它。

+1

我明白。另一个问题 - 如何在一个类中重写并添加具有相同名称的新成员(隐藏第一个)。它可能在两个类 – Michael

+0

@Michael:你可以修改'A'吗? – Dennis

+0

是的,你可以修改A,但希望A.Text是抽象的 – Michael

0

可以排序与接口​​做到这一点:

interface A 
{ 
    // The interface requires that Text is *at least* read only 
    string Text { get; } 
} 

class B : A 
{ 
    string text = ""; 

    // Implement Text as read-write 
    public string Text 
    { 
     get { return text; } 
     set { text = value; } 
    } 
} 

如果这不会为你工作,你可以简单地添加一个TextEx属性,它是可读写的:

public string TextEx 
{ 
    get { return text; } 
    set { text = value; 
} 

public string Text 
{ 
    get { return text; } 
}